为什么我可以用NULLPTR初始化自动推导的指针?
我试图做类似的事情:
auto foo = int*(nullptr);
使用VC ++没有编译错误消息:
类型名称不允许
,而使用GCC 8.2不允许使用:
在'int''
之前预期的主要表达式
我真的很好奇为什么这似乎是一种非法语法。在我看来,这应该是可以的,因为可以这样初始化文字。
auto foo = int(2);
我想到的唯一方法是要使这个类型的别名或这样做:
auto foo = std::add_pointer_t<int>(nullptr);
我尝试了谷歌搜索,但坦率地说,我什至不知道如何正确提出这个问题,因为我的标准人很弱。任何见解都将不胜感激!
I was trying to do something similar to this:
auto foo = int*(nullptr);
Which with VC++ doesn't compile with the error message:
Type name is not allowed
And with GCC 8.2 doesn't compile with:
Expected primary expression before 'int'
I was really curious as to why this appears to be an illegal syntax. In my mind it should be fine since literals can be initialized like this.
auto foo = int(2);
The only way I could think off to get this to work was to either make a type alias or do this:
auto foo = std::add_pointer_t<int>(nullptr);
I tried googling for this but frankly I don't even know how to properly formulate this question since my standardese is weak. Any insight would be appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
int*
是“派生的声明器类型” (不是标准术语,但对于推理这一点很有用)。功能样式的铸件符号(这是int(2)
IS)只能包含a您必须要:
以C风格的铸件的形式写出来:
或以c ++的形式 - 样式 - 铸造:
或别名指针类型:
int*
is a "derived declarator type"(not a standard term, but useful for reasoning about this). A functional style cast notation (which is whatint(2)
is) can only contain a "A simple-type-specifier or typename-specifier". A derived declarator type doesn't fall under either category.You have to either:
write it out in the form of a C-style cast:
or in the form of a C++-style cast:
or alias the pointer type:
int*(nullptr)
不起作用,因为只有单个字类型名称可以在函数铸造表达式。请注意,int*
不是单字的类型名称,而int
is(然后int(2)
正常工作)。作为解决方法,您可以使用
typedef
,或将其更改为C风格的铸造表达式。
int*(nullptr)
doesn't work because only single-word type name could be used in functional cast expression. Note thatint*
is not a single-word type name, whileint
is (and thenint(2)
works fine).As the workaround, you can use
typedef
,or change it to c-style cast expression.