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
}
  • Clang accepts the whole program.
  • GCC accepts the specialization definition, but ignores it in A<1>{}.
  • MSVC complains on such specialization:
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?

Source: Windows Questions C++

LEAVE A COMMENT