2

I have a class template with some template aliases. Since I am only using a closed set of types on the template, I would like to specialize and explicitly instantiate them. I currently have this:

// Header
template <typename T>
struct Literal {
    Literal(std::string_view);
};

using StringLiteral = Literal<std::string>;

// Source:
StringLiteral::Literal(std::string_view){/*...*/}

I assumed that I would need an extern template StringLiteral or something, but this seems to work. I am able to use StringLiteral in an entirely different TU than than the one the specialization lives in.

My question is, is this legal? And if so, why is explicit instantiation not needed? We couldn't implicitly instantiate the template in another TU since we do not have a definition for the constructor.

Additionally, the usage of the template alias to specialize seems weird to me, is it correct?

user975989
  • 2,578
  • 1
  • 20
  • 38
  • I seem to remember the linker sees multiple implementations of the template class, assumes they are all the same picks one and discards the others, if you're lucky it'll pick the right one – Alan Birtles Mar 07 '19 at 07:36

0 Answers0