`type_alias<char[N]>{}` VS `char[N]{}` 在函数的参数中 [英] `type_alias<char[N]>{}` VS `char[N]{}` in function's argument
问题描述
- 环境:x86-64 Clang 6.0.0
- Environment: x86-64 Clang 6.0.0
函数定义:
void foo(const char*) {}
foo(char[16]{});//休斯顿,有问题!
foo(type_alias
{});//编译愉快
type_alias
很简单:
template<typename T>
using type_alias = T;
作为注释,case 1
不能编译,而 case 2
可以.
As comment notes, case 1
cannot compile while case 2
can.
我知道带有 using
的 alias declarations
不是文本替换(如 #define
),它是类型的同义词.
I know that alias declarations
with using
is not text substitution(like #define
) and it is a synonym for the type.
但我仍然不知道如何解释这种情况.然后我给 GCC 一个 try
>:
But I still cannot figure out how to account for this situation. Then I give GCC a try
:
prog.cc: In function 'int main()':
prog.cc:11:7: error: expected primary-expression before 'char'
foo(char[16]{});
^~~~
prog.cc:12:7: error: taking address of temporary array
foo(type_alias<char[16]>{});
^~~~~~~~~~~~~~~~~~~~~~
啊,GCC反而给了我一个错误!然后我用两个编译器的不同版本编译它:
Ah, GCC gave me an error instead! Then I compile it with different versions of the two compilers:
- Clang 的
case 1
错误消息是:
- Clang's error message for
case 1
is:
prog.cc:11:11: 错误:函数式强制转换或类型构造的预期为 '('
prog.cc:11:11: error: expected '(' for function-style cast or type construction
foo(char[16]{});
~~~~^
Clang 让
case 2
通过.GCC 禁止这两种情况都通过竞争.
case 1
和case 2
的错误消息已在上面列出.GCC's forbid both the two cases to pass competition. Error messages for
case 1
andcase 2
have been listed above.顺便说一句,对于Clang,我也用
pedantic-errors
进行了测试,但没有任何改变.BTW, for Clang, I have also tested with
pedantic-errors
, but nothing changed.问题:
- 对于
case 2
:Clang、GCC,谁符合标准?标准(语言律师)中有任何规范吗? - 对于
case 1
:谁的错误信息更正确(IOW,符合标准)?
- For
case 2
: Clang, GCC, who conforms the standard? Any spec in standard(language lawyer)? - For
case 1
: Whose error message is more correct(IOW, conforms the standard)?
正如 VTT 评论的那样,对于
case 1
,它应该是foo(const char[16]{});
.为这个错误道歉.As VTT comments, for
case 1
, it should befoo(const char[16]{});
. Apology for this mistake.但是Clang可以编译
foo(type_alias<char[16]>{});
.这似乎是一个错误?But Clang can compile
foo(type_alias<char[16]>{});
. It seems to be a bug?推荐答案
嗯,
type_alias
等价于{} (cv T){}
,不要cv T{}
.当T
是一个数组时,这种区别很重要:Well,
type_alias<cv T>{}
is equivalent to(cv T){}
, not tocv T{}
. This distinction matters whenT
is an array:foo((const char[16]){}); // OK foo(type_alias<const char[16]>{}); // OK foo(const type_alias<char>[16]{}); // KO foo(const char[16]{}); // KO
演示:https://wandbox.org/permlink/KGf3HVqN3USq6yy8
对于case 2:Clang,GCC,谁符合标准?标准(语言律师)中的任何规范?
For case 2: Clang, GCC, who conforms the standard? Any spec in standard(language lawyer)?
两者都可以,都接受
foo(type_alias<char>[16]{})
,但是 gcc 警告你(并且因为你用-Werror
,这个警告变成了错误;).Both does, both accept
foo(type_alias<char>[16]{})
, but gcc warns you about it (and since you compiled with-Werror
, this warning is turned into an error ;).这篇关于`type_alias<char[N]>{}` VS `char[N]{}` 在函数的参数中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- 对于