【发布时间】:2021-04-10 09:49:52
【问题描述】:
#include <typeinfo>
#include <iostream>
using namespace std;
template<typename T> void f1(T&& a) {}
void f2(int&& a) {}
int main()
{
int i = 0;
f1(i);//This is fine
f2(i);//This gives compilation error
}
为什么同一种调用有不同的编译规则?
模板化f1 接受lvalue,但非模板化函数不接受lvalue。为什么?
f1 for int 的模板实例化看起来不像 f2?
我可以用std::move 修复编译问题。但是上面的一个没看懂。
test.cpp:在函数“int main()”中:test.cpp:13:7:错误:无法将“int”左值绑定到“int&&”f2(i);
test.cpp:7:6: 注意:初始化 'void f2(int&&)' void f2(int&& a) {}
的参数 1
【问题讨论】:
-
对于具体类型,
&&表示 RValue 引用。对于模板参数T,T&&表示通用引用。尽管看起来非常相似,但这是有区别的。 Scott Meyers: Universal References in C++11我曾经发过minimal reproducible example来提醒自己(以防一些疑问/困惑回到我身边):RValue Ref. vs. Universal Ref. -
这些链接很好。
标签: c++ templates rvalue-reference