int&amp;&amp;和和模板<class t =“”> T&amp;&amp; </class>

时间:2014-07-24 05:14:06

标签: c++ templates c++11

#include <iostream>
#include <typeinfo>

struct C
{
  template<class T>
  C(T && t) { std::cout << typeid(T).name() << std::endl; }
};

struct D
{
  D(int && t) { }
};

int main() 
{
    int i = 1;
    std::cout << typeid(i).name() << std::endl;

    C c(i);     // OK
    D d(i);     // error
}

D d(i);无法编译:

foo.cc:22:7: error: cannot bind 'int' lvalue to 'int&&'

但是,将其评论出来后,生成的输出为:

i
i

表明T被推断为intD(int &&)如何无法绑定但C(int &&)成功?

1 个答案:

答案 0 :(得分:2)

根据评论中提供的所有重要信息回答我自己的问题:

  • int &&只能绑定到rvalues
  • T&&可以绑定到rvalues和lvalues

标准没有特定术语可以绑定到rvalues和左值&#34;,因此Scott Meyers创造了术语通用引用和{{3}解释一切。

基本原理:非通用版本用于移动语义,但this article by him需要通用版本。

在开发C ++ 11期间,有些人认为应该使用不同的语法进行移动而不是转发,但是它们会丢失并且&&被用于两者,在推导的上下文中使用T&&意思是转发&&在其他上下文中意味着移动

Jonathan Wakely的

perfect forwarding;事实上,我的问题可以作为该问题的副本而被关闭。

此外,T const &&不是通用引用,可能是因为它对转发无用。

相关问题