C ++中的模板和std :: forward

时间:2019-05-27 08:45:52

标签: c++

第一行代码将返回112,但为什么呢? 1的类型不应该为int&&吗?为何它在第二个代码示例(即返回312)中起作用?

void fun(int&) { cout << 1; }
void fun(int const&) { cout << 2; }
void fun(int&&) { cout << 3; }

template
<typename T>
void fun2(T&& t) { fun(t); }

int main() {
  int x{};
  int const y{};
  fun2(1);
  fun2(x);
  fun2(y);
}
void fun(int&) { cout << 1; }
void fun(int const&) { cout << 2; }
void fun(int&&) { cout << 3; }

template
<typename T>
void fun2(T&& t) { fun(std::forward<T>(t)); }

int main() {
  int x{};
  int const y{};
  fun2(1);
  fun2(x);
  fun2(y);
}

1 个答案:

答案 0 :(得分:0)

std :: forward基本上意味着您希望在将调用参数传递/转发给另一个函数时保留其左值或右值。

因此,在第二个示例中,您保留了右值,而在第一个示例中,您将t用作了左值引用。

例如,您可能想在这里阅读更多关于通用/转发参考的内容: https://isocpp.org/blog/2012/11/universal-references-in-c11-scott-meyers