模板和std ::在C 中向前

template and std::forward in c++

本文关键字:std      更新时间:2023-10-16

代码的第一行将返回 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);
}

std ::前进基本上意味着您要在传递/转发到另一个函数时要保留调用参数的lvaluentes或rvaluentes。

因此,在第二个示例中,您可以保留rvaluentes,而在第一个示例中,您将t作为lvalue参考。

您可能想在Universal/Expracting参考文献上阅读更多信息:https://isocpp.org/blog/2012/11/universal-references-in-c11-scott-meyers

相关文章:
  • 没有找到相关文章