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

问题描述

以下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,是否也需要诊断?

解决方法

即使未使用n,也需要诊断吗?

不。适用规则是[temp.res.general]/8

可以在任何实例化之前检查模板的有效性。

该程序格式错误,如果出现以下情况,则无需进行诊断:

  • 如果模板中的语句或模板未实例化,则无法为模板或constexpr的子语句生成有效的专业化,或者
  • ...
  • 由于模板不依赖模板参数,因此假设模板紧随其定义之后的假想实例化将不正确,或者
  • ...

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