【问题标题】:Templated rvalue reference vs non templated compilation errors模板右值引用与非模板编译错误
【发布时间】: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

【问题讨论】:

标签: c++ templates rvalue-reference


【解决方案1】:

在模板上下文中,T&amp;&amp; 不仅仅是一个右值引用,它还是一个forwarding reference。

在调用f1(i) 中,T 是deduced 作为int&amp;,并且根据reference collapsing 规则,int&amp; &amp;&amp; 变为int&amp;,即左值引用。

这就是它能够绑定到int x的原因。

在f2 中的非模板上下文中,int&amp;&amp; 只是一个右值引用,没有额外的魔法。它只会绑定到右值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-13
    相关资源
    最近更新 更多