The "inlineness" of template class variables

J

Juha Nieminen

A static variable of a regular class cannot be declared "inline",
which means that its definition has to be in one single compilation
unit (or else you'll get a linker error).

This limitation does not hold for templated classes, where it's
perfectly possible to have static member variables whose definitions
end up in multiple compilation units without it causing a linker error
(iow. the static member variable is effectively "inline").

In other words, you can safely have something like this in a header
file:

template<typename T>
class Test
{
static T aStaticVar;
};

template<typename T>
T Test<T>::aStaticVar = 0;

Even though the definition of the variable will end up in more than
one compilation unit, it's ok.

However, for some reason this "inlineness" does not extend to
specializations of that definition. For example, if you had something
like this in the same header file:

template<>
long Test<long>::aStaticVar = 5;

then you get linker errors (at least with gcc) if the header is included
in more than one compilation unit.

Is this really so, and why?
 
M

Marcel Müller

Is this really so, and why?

Well, the original idea beyond C++ is that anything with static linkage
has to be defined in exactly one compilation unit. But with template
this did not stay very long because the number of potential
instantiations is no longer finite and explicit template instantiations
are awful and error prone. So an exception for templates has been added.
It causes the symbol to become weak which means that the unavoidable
redefinitions in different compilation units are silently removed by the
linker.

Most platforms support other symbols to be specified as weak too. But
this is platform dependent.


Marcel
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,540
Members
45,025
Latest member
KetoRushACVFitness

Latest Threads

Top