c++ - 它是如何解析的:使用大括号的init列表构造未命名的临时文件

标签 c++ c++11

我最近yet again encountered表示法

( const int[10] ){ 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 }

我记得C和C++都允许使用,但是通过完全不同的语言机制。

我相信在C++中,正式的观点是它是通过epxlicit类型转换(T) cast-expression的未命名临时结构的构造,该构造将简化为static_cast,它通过C++ 11§5.2.9/ 4构造对象:

an expression e can be explicitly converted to a type T using a static_cast of the form static_cast<T>(e) if the declaration T t(e); is well-formed, for some invented temporary variable t (8.5)



但是,C++ 11§5.4/ 2将cast-expression语法定义为一元表达式或递归( type-id ) cast-expression,其中单个基本情况是简化为一元表达式。

据我所知,大括号的init列表不是表达式吗?

另一种观点可能是它是通过函数符号C++ 11§5.2.3/ 3进行的显式类型转换,

a simple-type-specifier or typename-specifier followed by a braced-init-list creates a temporary object of the specified type



但据我所知,简单类型说明符不能包含括号,而类型名说明符涉及关键字typename吗?

最佳答案

根据C99(嗯,实际上是N1256,它是先前的草案)6.5.2.5/4:

A postfix expression that consists of a parenthesized type name followed by a brace-enclosed list of initializers is a compound literal. It provides an unnamed object whose value is given by the initializer list.



一些编译器-at least g++ and clang-在C++中提供C99复合文字作为扩展。语义上,表达
( const int[10] ){ 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 }

const int[10]类型的文字:decltype((const int[10]){ 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 })实际上是const int[10]请注意: g++版本之间在确切类型方面存在一些分歧:4.9之前的g++版本说decltype((const int[10]){ 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 })const int(&)[10]See this demonstration program

您可以通过功能符号通过显式类型转换在标准C++中获得相同的结果,但是您必须为数组类型定义类型别名,因为功能符号需要使用简单类型说明符:
using foo = const int[10];
foo{ 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };

Xeo's general alias template:
template <typename T>
using foo = T;
foo<const int[10]>{ 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };

关于c++ - 它是如何解析的:使用大括号的init列表构造未命名的临时文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62868999/

相关文章:

c++ - 包含在 std::regex 搜索中,使用 std::regex_token_iterator 从 std::sub_match 中排除

c++ - 允许运行时和编译时多态性的灵活方式?

c++ - 如何使 `std::is_empty_v<T> && sizeof(T) > 1` 为真的类型 T?

c++ - 怎么让这些成员元素能装进3个字节?

c++ - 将 OpenGL 用于 2D

c++ - 类字段在函数内部不可访问

c++ - 覆盖 std::locale 上的多个方面

c++ - 如何使用模板化构造函数调用 make_shared 或 make_unique

c++ - 将 const 引用返回到临时行为与本地 const 引用不同?

c++ - 有什么方法可以通过 SSH 连接打开和读取文件吗?