c++ - 直接初始化 unsigned short 的标准行为

标签 c++ syntax casting initialization language-lawyer

我今天注意到在示例代码中:

void print(unsigned short a) {
   std::cout << a << std::endl;
}

初始化和使用是这样的:

print(short (5));

但不是这样的:

print(unsigned short(6));

main.cpp:16:8: error: expected primary-expression before 'unsigned' print(unsigned short(6));

这与类型无关,因为这也有效:

typedef unsigned short ushort;
print(ushort (6));

Live example.

所以我开始搜索标准中关于值初始化的内容。结果一无所获:

The effects of value initialization are:

1) if T is a class type ...

2) if T is a non-union class type ...

2) if T is a class type ...

3) if T is an array type, ..

4) otherwise, the object is zero-initialized.

为便于阅读而进行了修改。 Original source .

POD的值初始化规则是什么?类型? unsigned 限定类型无法进行值初始化的原因是什么?这是否与它们是 rvalues 的事实有关?

最佳答案

What is the reason that unsigned qualified types can't be value initialized?

只是因为 functional cast expression 中只能使用单字类型名称, 而 unsigned short 不是单字类型名称; 是。

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) or int*(expression) are not valid), followed by a single expression in parentheses.

正如您所展示的,您可以使用 typedef 作为解决方法,或添加括号以将其更改为 c 风格的强制转换表达式,例如(unsigned short)(6),或 (unsigned short)6.

根据标准,§7.6.1.3/1 Explicit type conversion (functional notation) [expr.type.conv] :

A simple-type-specifier or typename-specifier followed by a parenthesized optional expression-list or by a braced-init-list (the initializer) constructs a value of the specified type given the initializer.

还有 simple-type-specifier :

simple-type-specifier:
  nested-name-specifier opt
 type-name
  nested-name-specifier template simple-template-id
  nested-name-specifier opt
 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 )

typename-specifier :

typename-specifier:
  typename nested-name-specifier identifier
  typename nested-name-specifier template opt
 simple-template-id

关于c++ - 直接初始化 unsigned short 的标准行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51893895/

相关文章:

javascript - 在javascript中,是否有检查每一层嵌入对象是否存在的语法快捷方式?

java - 将 List<MyObject> 转换为 List<MyInterface>

java - Android编程如何将小部件转换或转换为java字符串

c++ - 如何从文件名列表创建 IShellItemArray

java - ')' 预期 (java)

c++ - git_remote_fetch 返回错误消息 : "there is no TLS stream available"

mysql - SQL-选择不同值的计数

c++ - 两个指针之间的转换/转换

c++ - 使用类和命名空间差异/歧义

c++ - 条件变量卡在等待中