【发布时间】:2021-12-08 14:06:57
【问题描述】:
你好,我有这个来自 C++ 入门的例子:
template <typename T> void f(T&& x) // binds to nonconstant rvalues { std::cout << "f(T&&)\n"; } template <typename T> void f(T const& x) // lvalues and constant revalues { std::cout << "f(T const&)\n"; }
这是我测试输出的尝试:
int main(){
int i = 5;
int const ci = 10;
f(i); // f(T& &&) -> f(int&)
f(ci); // f(T const&) -> f(int const&)
f(5); // f(T &&) -> f(int&&)
f(std::move(ci)); // f(T&&) -> f(int const&&)
cout << '\n';
}
输出:
f(T&&)
f(T const&)
f(T&&)
f(T&&)
-
在书中,
f的版本被称为转发引用只绑定到非常量右值,但在main中,我传递了一个常量右值f(5)和f(std::move(ci)),但仍然是第一个版本调用。 -
有没有办法调用第二个版本
f(T const&)传递一个右值?我知道我可以明确地做到这一点:f<int const&>(5);或f<int const&>( std::move(ci) );但我想知道在哪里可以调用传入右值?谢谢! -
我认为
f的转发参考版本之后的注释不正确:f(T&&) // binds to nonconstant rvalues因为它可以绑定到常量右值,例如:f(std::move(ci)); // f(int const&&) and not f(int const&)
【问题讨论】:
-
我开始觉得这本入门书不应该再出现在推荐书单上了……
标签: c++ template-argument-deduction