[英]Explicit type conversion (functional notation) with simple-type-specifier
Porting some code I have discovered that line 移植一些代码我发现了这一行
unsigned char uc = unsigned char(c);
is accepted by MSVC but rejected by GCC. 被MSVC接受但被GCC拒绝。 Is this syntax correct? 这种语法是否正确?
Standard says that 标准说
A simple-type-specifier (7.1.7.2) ... followed by a parenthesized optional expressionlist or by a braced-init-list (the initializer) constructs a value of the specified type given the initializer 简单类型说明符(7.1.7.2)...后跟带括号的可选表达式列表或通过braced-init-list(初始化程序)构造给定初始化程序的指定类型的值
Does it mean that MS is right? 这是否意味着MS是对的? Is unsigned char
a 'simple-type-specifier'? unsigned char
是'simple-type-specifier'吗?
GCC and CLANG are correct, the code is not valid. GCC和CLANG是正确的,代码无效。
Simple type specifier is single-word type name: 简单类型说明符是单字类型名称:
The simple type specifiers are 简单的类型说明符是
simple-type-specifier: nested-name-specifieropt type-name nested-name-specifier template simple-template-id nested-name-specifieropt template-name char char16_t char32_t wchar_t bool short int long signed unsigned float double void auto decltype-specifier type-name: class-name enum-name typedef-name simple-template-id decltype-specifier: decltype ( expression ) decltype ( auto )
unsigned char
is not a simple-type-specifier, it's a combination of simple-type-specifiers, as shown in Table 9 from standard. unsigned char
不是简单类型说明符,它是简单类型说明符的组合 ,如表9中的标准所示。
Table [tab:simple.type.specifiers] summarizes the valid combinations of simple-type-specifiers and the types they specify. Table [tab:simple.type.specifiers]总结了simple-type-specifiers的有效组合及其指定的类型。
Table 9 — simple-type-specifiers and the types they specify 表9 - 简单类型说明符及其指定的类型
Specifier(s) Type ... unsigned char “unsigned char” ...
Here 's an explanation from cppreference.com: 以下是cppreference.com的解释:
2) The functional cast expression consists of a simple type specifier or a typedef specifier (in other words, a single-word type name:
unsigned int(expression)
orint*(expression)
are not valid), followed by a single expression in parentheses. 2)函数强制转换表达式由简单的类型说明符或typedef说明符组成(换句话说,单字类型名称:unsigned int(expression)
或int*(expression)
无效),后跟单个表达式括号。
或者您可以使用:
unsigned char uc = static_cast<unsigned char>(c);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.