以下是实际代码的人为例子:
int** Ptr = 0;
decltype(Ptr[0]) Test = (int*)0;
我收到错误:
error C2440: ‘initializing’: cannot convert from ‘int *’ to ‘int *&’
我不知道为什么我得到了这个,因为从我对decltype的理解(纠正我,如果我错了)它只需要你给它的任何表达并将其解析为它的实际类型.在这种情况下,Ptr [0]是一个int *所以我期待:int * Test =(int *)0;
我错过了什么?为什么我会收到这个错误?
解决方法:
如果我们转到草案C标准部分7.1.6.2简单类型说明符[dcl.type.simple]并查看他的情况.对于decltype,它开始说:
For an expression e, the type denoted by decltype(e) is defined as follows:
我们看到,在这种情况下,表达式不是id-expression,也不是类成员访问,这将给出你期望的结果(强调我的):
- if e is an unparenthesized id-expression or an unparenthesized class member access (5.2.5), decltype(e)
is the type of the entity named by e. If there is no such entity, or if e names a set of overloaded functions,
the program is ill-formed;
但结果是左值:
- otherwise, if e is an lvalue, decltype(e) is T&, where T is the type of e;
这导致参考.
正如M.M指出std::remove_reference可以用来获得你想要的结果:
std::remove_reference<decltype(Ptr[0])>::type Test = (int*)0;
作为T.C.指出std::decay也是一种选择,而且更短:
std::decay<decltype(Ptr[0])>::type Test = (int*)0;