未使用的常量变量模板的默认初始化

Default initialization of unused constant variable template

以下program

template<typename = void> 
const int n;

gcc编译成功,clang报错:

# error: default initialization of an object of const type 'const int'
const int n;
          ^
            = 0

有道理。

如果使用 n,gcc 会报错,但即使未使用 n,是否也需要诊断?

is a diagnostic required even if n is unused?

没有。适用的规则是 [temp.res.general]/8:

The validity of a template may be checked prior to any instantiation.

The program is ill-formed, no diagnostic required, if:

  • no valid specialization can be generated for a template or a substatement of a constexpr if statement within a template and the template is not instantiated, or
  • ...
  • a hypothetical instantiation of a template immediately following its definition would be ill-formed due to a construct that does not depend on a template parameter, or
  • ...

所以两个编译器都符合标准。