1

While trying to understand how all the template magic in C++ 20 works I stumbled upon the following (which is probably not really related to C++ 20):

My compiler (Visual C++ 2022) accepts the following code:

template<typename X,typename Y>
constexpr int UselessVar = 42;

template<typename X>
char* UselessVar <X,X> = "Donald Duck";

auto Blabla1 = UselessVar<int,int>;
auto Blabla2 = UselessVar<int*,int**>;

Code compiles and indeed Blabla1 is a 'constexpr int' and Blabla2 a 'char*'.

I am wondering: Does a template specialisation really allow me to change both "constness" and type of the underlying variable or is this a glitch of this compiler? This seems pretty weird to me. Beside use cases like "changing the type of a return value from a base class to a derived class" I cannot really think of a good use-case for something in that direction and somehow from "gut-feeling" I would assume that this kind of "changing the type to something completely different" should be forbidden?!

1 Answers1

1

A specialized variable, function, or a class is a fully discrete, variable, function, or class that has absolutely nothing to do, whatsoever, inherently, to the variable, function, or a class template that it specializes.

A declaration of a specialized template is just an ordinary variable, function, or a class declaration. Just because its name happens to have some kind of a similarity to some other variable, function, or class doesn't place any obligations on it.

Just like there's nothing wrong with:

constexpr int UselessVar1 = 42;

char* UselessVar2 = "Donald Duck";

there's also nothing wrong with

template<typename X,typename Y>
constexpr int UselessVar = 42;

template<typename X>
char* UselessVar <X,X> = "Donald Duck";

either. The template parameters are just a part of the object's name.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148
  • There was a comment above that pointed me to [link](https://stackoverflow.com/questions/19108345/c1y-c14-variable-template-specialization) which is basically the exact same question (and the exact same answer). So this is really not forbidden, just another way to "blow your leg of" in C++. Thanks for the answer anyway! – Gregor Grunz Nov 27 '22 at 16:14