假设我在类set_value
中有一个方法的两个重载,每个方法都采用通用引用。我希望有一个函数调用另一个来避免代码重复,但我不确定哪个是给另一个函数的通用引用的正确方法。
template <typename U>
void set_value(U&& value) {
this->value_ = std::forward<U>(value);
}
template <typename U>
void set_value(U&& value, int overloaded) {
// which is the correct way to use the other `set_value` overload?
set_value(value); // just use value directly?
set_value(std::forward<U>(value)); // or should I forward it?
}
答案 0 :(得分:0)
如果您想完美转发value
,请使用std::forward
即使value
可能绑定到右值,但当您在set_value
内按名称使用它时,它也是左值。因此,如果执行set_value(value);
,则单参数重载中的通用引用将绑定到左值引用。
我们可以通过添加以下内容来确认:
template<class T> class TD; // Allows us to view type deduction results in
// the form of compilation errors.
// (From "Effective Modern C++")
...
template <typename U>
void set_value(U&& value) {
TD<decltype(value)> td;
}
...
int i;
set_value(i, 0);
set_value(3, 0);
使用转发时,这会给您一个编译错误,该错误会显示value
的{{1}}类型int&
。如果您注释掉该语句,则会set_value(i, 0);
显示set_value(3, 0);
类型为value
的编译错误。
如果您删除转发,则在两种情况下都会获得int&&
。