c++language-lawyeruninitialized-constant

Default initialization of unused constant variable template


The following program:

template<typename = void> 
const int n;

is compiled successfully by gcc, but clang gives an error:

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

which makes sense.

gcc does give an error if n is used, but is a diagnostic required even if n is unused?


Solution

  • is a diagnostic required even if n is unused?

    No. The applicable rule is [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
    • ...

    So both compilers are complying with the Standard.