decltype错误C2440无法从'int *'转换为'int *&' [英] decltype error C2440 cannot convert from 'int *' to 'int *&'

查看:743
本文介绍了decltype错误C2440无法从'int *'转换为'int *&'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是一个实际代码的例子:

The following is a contrived example of the actual code:

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

我得到错误:


错误C2440:'initializing':无法从'int *'转换为'int *&'

error C2440: 'initializing': cannot convert from 'int *' to 'int *&'

我不知道为什么我得到,因为从我的理解 decltype (纠正我,如果我错了)它只是接受任何表达式你给它,并解决它到其实际类型。在这种情况下, Ptr [0] 是一个 int * 所以我期待: int * Test =(int *)0;

I'm not sure why I'm getting that since from my understand of decltype (correct me if I'm wrong) it just takes whatever expression you give it and resolve it to its actual type. In this case Ptr[0] is an int* so I'm expecting: int* Test = (int*)0;

我缺少什么?为什么我得到这个错误?

What am I missing? Why am I getting that error?

推荐答案

如果我们去草稿C ++标准部分 7.1.6.2 简单类型说明符[dcl.type.simple],看看他的情况。对于decltype,它开始说:

If we go to the draft C++ standard section 7.1.6.2 Simple type specifiers [dcl.type.simple] and see what he cases are. For decltype it starts out saying:


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

For an expression e, the type denoted by decltype(e) is defined as follows:

我们看到,在这种情况下,表达式不是一个id表达式,也不是一个类成员访问,这将给出你期望的结果> emphasis mine ):

We see that in this case the expression is not a id-expression nor a class member access, which would give the result you expected(emphasis mine):



  • 如果 e是未加括号的id表达式非公开类成员访问(5.2.5),decltype(e)
    是由e
    命名的实体的类型。如果没有这样的实体,或者如果e命名一组重载的函数,
    程序是不成形的;

  • 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;

但结果是左值:



  • > e是一个左值,decltype(e)是T& ,其中T是e的类型;

  • otherwise, if e is an lvalue, decltype(e) is T&, where T is the type of e;

这会产生一个引用。

由于MM指出 std :: remove_reference 可用于获取所需的结果:

As M.M point out std::remove_reference could be used to obtain the result you want:

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

指出 std :: decay 也是一个选项,缩写为:

As T.C. points out std::decay is also an option and is shorter:

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

这篇关于decltype错误C2440无法从'int *'转换为'int *&amp;'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆