c++templateslanguage-lawyerpartial-specialization

Can template partial specialization narrow the argument type in C++?


In the next program, struct template A<int> has a specialization A<char>:

template <int>
struct A { constexpr operator int() { return 1; } };

template <char c>
struct A<c> { constexpr operator int() { return 2; } };

int main() {
    static_assert( A<1000>{} == 1 ); //ok in Clang and GCC
    static_assert( A<1>{} == 2 ); //ok in Clang only
}
error C2753: 'A<c>': partial specialization cannot match argument list for primary template

Demo: https://gcc.godbolt.org/z/Ef95jv5E5

Which compiler is right here?


Solution

  • The active CWG issue 1647 mentions exactly this case of specializing an int non-type template parameter to a char.

    It also mentions that the standard is currently lacking wording to handle type mismatches between non-type template parameters in primary templates and their partial specializations and that there is implementation divergence on the issue.