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?
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?