名称中带有 space 的临时类型的统一初始化的正确语法,如 unsigned int
Correct syntax for uniform initialization of temporary of type with space in name like unsigned int
我正在尝试将 T 类型的 x 传递给需要 unsigned int
的函数 foo
,但我不确定 T 是什么,因为它是在其他模块中声明的 typedef。 foo
和 T
都不是我可以修改的。如果发生缩小,我希望编译器警告我。
所以我正在尝试:
typedef int T;
void foo(unsigned int x);
void bar(){
T x;
foo(unsigned int{x});
}
不幸的是在 gcc 9.2 上。这给了我一个编译错误:
<source>: In function 'void bar()':
<source>:5:9: error: expected primary-expression before 'unsigned'
foo(unsigned int{x});
^~~~~~~~
Compiler returned: 1
如果我将违规行更改为:
foo((unsigned int){x});
然后问题就消失了,我得到了一个正确的警告,指出发生了缩小:
<source>: In function 'void bar()':
<source>:5:25: warning: narrowing conversion of 'x' from 'T {aka int}' to 'unsigned int' inside { } [-Wnarrowing]
foo((unsigned int){x});
^
Compiler returned: 0
太棒了!
不幸的是,这种语法不适用于 Visual Studio 2019 16.2.5,因为我得到:
E0029
C4576
C2397
此行中的错误。其中C4576为"a parenthesized type followed by an initializer list is a non-standard explicit type conversion syntax".
那么这种情况下的标准显式类型转换语法是什么?
https://en.cppreference.com/w/cpp/language/explicit_cast第5)点说必须是单字型。
如果超过一个字怎么办(long long、unsigned long int等?)
在你的情况下,你可以只写 unsigned
而不是 unsigned int
。但更通用的解决方案是创建类型别名:
void bar(T x) {
using U = unsigned int;
foo(U{x});
}
我正在尝试将 T 类型的 x 传递给需要 unsigned int
的函数 foo
,但我不确定 T 是什么,因为它是在其他模块中声明的 typedef。 foo
和 T
都不是我可以修改的。如果发生缩小,我希望编译器警告我。
所以我正在尝试:
typedef int T;
void foo(unsigned int x);
void bar(){
T x;
foo(unsigned int{x});
}
不幸的是在 gcc 9.2 上。这给了我一个编译错误:
<source>: In function 'void bar()':
<source>:5:9: error: expected primary-expression before 'unsigned'
foo(unsigned int{x});
^~~~~~~~
Compiler returned: 1
如果我将违规行更改为:
foo((unsigned int){x});
然后问题就消失了,我得到了一个正确的警告,指出发生了缩小:
<source>: In function 'void bar()':
<source>:5:25: warning: narrowing conversion of 'x' from 'T {aka int}' to 'unsigned int' inside { } [-Wnarrowing]
foo((unsigned int){x});
^
Compiler returned: 0
太棒了! 不幸的是,这种语法不适用于 Visual Studio 2019 16.2.5,因为我得到: E0029 C4576 C2397 此行中的错误。其中C4576为"a parenthesized type followed by an initializer list is a non-standard explicit type conversion syntax".
那么这种情况下的标准显式类型转换语法是什么? https://en.cppreference.com/w/cpp/language/explicit_cast第5)点说必须是单字型。 如果超过一个字怎么办(long long、unsigned long int等?)
在你的情况下,你可以只写 unsigned
而不是 unsigned int
。但更通用的解决方案是创建类型别名:
void bar(T x) {
using U = unsigned int;
foo(U{x});
}