decltype错误C2440无法转换为' int *'到' int *&'

时间:2015-11-09 01:01:03

标签: c++ decltype

以下是实际代码的设计示例:

int** Ptr = 0;
decltype(Ptr[0]) Test = (int*)0;

我收到错误:

  

错误C2440:'初始化':无法转换为' int *'到' int *&'

我不确定为什么我会这样做,因为从我对decltype的理解(纠正我,如果我错了)它只是采取你给它的任何表达并解决它到它的实际类型。在这种情况下,Ptr[0]int*,所以我期待:int* Test = (int*)0;

我错过了什么?为什么我会收到这个错误?

2 个答案:

答案 0 :(得分:5)

如果我们转到草案C ++标准部分apply plugin: 'com.android.application'简单类型说明符[dcl.type.simple]并查看他的案例。对于decltype,它开始说:

  

对于表达式e,由decltype(e)表示的类型定义如下:

我们看到,在这种情况下,表达式不是id-expression,也不是类成员访问,它会给出你期望的结果(强调我的):

  
      
  • 如果 e是未加密码的id-expression或未加括号的类成员访问(5.2.5),则decltype(e)   是由e 命名的实体的类型。如果没有这样的实体,或者e命名一组重载函数,   该计划格式不正确;
  •   

但结果是左值:

  
      
  • 否则,如果 e是左值,则decltype(e)为T& ,其中T是e的类型;
  •   

导致参考。

正如M.M指出std::remove_reference可以用来获得你想要的结果:

7.1.6.2

作为T.C.指出std::decay也是一种选择,而且更短:

std::remove_reference<decltype(Ptr[0])>::type Test = (int*)0;

答案 1 :(得分:2)

除了所有其他答案,您也可以只使用

int ** ptr = 0;
decltype(+ptr[0]) test = (int*)0;
// (+*p) is now an r-value expression of type int, rather than int&

此处使用的一些规则是:

  • 如果表达式的值类别为lvalue,则decltype产生T&;
  • 如果表达式的值类别为prvalue,则decltype产生T。

还要注意,如果将对象的名称加括号,则将其视为普通的左值表达式,因此decltype(x)和decltype((x))通常是不同的类型。 [摘录自https://en.cppreference.com/w/cpp/language/decltype]

http://www.cplusplus.com/forum/beginner/149331/见过
有关 decltype 的更多信息,请点击此处:https://en.cppreference.com/w/cpp/language/decltype