1

The following code fails to compile when the template parameter T is a fundamental type such as int (on gcc 4.8). Is this standard conforming behaviour? My understanding of std::declval was that it always resolves to either a T&& or T&.

template <class T>
void foo(T&& val)
{
  std::cout << noexcept(std::declval<typename std::decay<T>::type>() = val);
}

struct bar { };
bar b;
foo(b); // okay

int a;
foo(a); // error: using xvalue (rvalue reference) as lvalue

The error occurs at the point of assigning val to the std::declval expression.

It works if I remove the std::decay and use std::declval<T> directly, but I'm not sure why. The decayed type should just be int and so std::declval<int>() should have a return type of int&& shouldn't it?

4

1 回答 1

3

您正在尝试分配给右值。std::declval<int>()正确返回一个类型int&&。它没有名字,所以它是类型的右值(更准确地说,xvalue)int。然后,您尝试分配给val这个右值,这对于基本类型是非法的。

这是一个以简化形式(不带 )演示问题的现场示例declval

于 2013-10-01T09:50:32.913 回答