可以使用 C++17 中的类模板 std::optional,避免使用 std::forward 重复传递同一变量的情况。
具体代码示例:
#include
#include
#include
template
void foo(std::optional&& arg)
{
if(arg) {
//使用 arg
//...
}
}
int main()
{
int x = 42;
foo(std::forward(x));
return 0;
}
此代码使用 std::optional 模板类来替换了原来使用 std::forward 传递同一变量的写法。
下一篇:避免重复使用相同的函数