( const int[10] ){ 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 }
我记得它在 C 和 C++ 中都是允许的,但通过完全不同的语言机制。
我相信在 C++ 中,正式的观点是它是通过显式类型转换 (T)
构造一个未命名的临时对象。 cast-expression 将减少为 static_cast
,通过 C++11 §5.2.9/4 构造一个对象:
” an expression
e
can be explicitly converted to a typeT
using astatic_cast
of the formstatic_cast<T>(e)
if the declarationT t(e);
is well-formed, for some invented temporary variablet
(8.5)
然而,cast-expression 语法由 C++11 §5.4/2 定义为 unary-expression 或递归的 (
类型 ID )
cast-expression,其中单个基本情况是简化为 unary-expression。
据我所知,braced init-list 不是表达式?
另一种观点可能是它是通过函数表示法进行的显式类型转换,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
但据我所知,simple-type-specifier 不能涉及括号,而 typename-specifier 涉及关键字 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++ 中通过函数式表示法进行显式类型转换,但您必须为数组类型定义类型别名,因为函数式表示法需要 simple-type-specifier:
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++ - 怎么解析: constructing unnamed temporary with braced init list,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24385410/