Home  >  Q&A  >  body text

关于C++模板实参推断的疑问

在C++ Primer中第16章第5节有讲到:

//原始的、最通用的版本
template <class T> struct remove_reference {
typedef T type;
};
template <class T> struct remove_reference<T&>//左值引用
{typedef T type;}
template <class T> struct remove_reference<T&&>//右值引用
{typedef T type;}
int i;
//decltype(42)为int,使用原始模板
remove_reference<decltype(42)>::type a;
//decltype(i)为int&,使用第一个(T&)部分特例化版本
remove_reference<decltype(i)>::type b;
//decltype(std::move(i))为int&&,使用第二个(即T&&)部分特例化版本
remove_reference<decltype(std::move(i))>::type c;

为什么decltype(i)是int&,难道不应该是int吗?这好像与C++ Primer第二章讲decltype时说的不一样啊?

PHPzPHPz2714 days ago769

reply all(1)I'll reply

  • 高洛峰

    高洛峰2017-04-17 15:27:58

    gcc 6.2 is int.
    I don’t know how the C++ specification is written, but my test under gcc 6.2 is int, not int&. If
    is deduced to be int&, then there is a syntax error here.
    Because

    remove_reference<decltype(i)>::type b;
    // 如果前面推导出来是 int& ,那么 b 引用谁呢?

    reply
    0
  • Cancelreply