`template<typename>;` 是合法的 C++ 吗?

Is `template<typename>;` legal C++?

GCC and Clang 不同意 template<typename>; 是否是全局范围内 C++ 中的有效语句。

我希望它在 C++ 标准中是不允许的,因为模板化属于声明语句,而不属于表达式语句,因此也不属于 null 语句(语句 ;)。

那么,这是 Clang 中的错误吗?

这是 clang 长期存在的特殊行为:缺少声明只会产生警告。就像这样:

int;

g++ 会显示错误,而 clang 只会显示警告。这与标准不矛盾。

warning: declaration does not declare anything [-Wmissing-declarations]

-Werror=missing-declarations 直截了当。

不是真的。该标准在 [temp]p2;

中明确禁止这样的声明

The declaration in a template-declaration (if any) shall

  • declare or define a function, a class, or a variable, or

  • define a member function, a member class, a member enumeration, or a static data member of a class template or of a class nested within a class template, or

  • define a member template of a class or class template, or

  • be a deduction-guide, or

  • be an alias-declaration.

empty-declaration 与这些子句中的任何一个都不匹配。现在该标准表示,需要一个实现来针对任何违反其规则的行为发出诊断消息,例如这个。请注意,它说 diagnostic,它没有指定是否发出警告或错误(甚至是注释)。编译器可以提供使您编写的内容有效的扩展,因为它不会改变格式良好的程序的含义。

所以不,两者都是对的。但是,clang 的行为是由于扩展,而不是标准指定的。