Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C++ > The "inlineness" of template class variables

Thread Tools

The "inlineness" of template class variables

Juha Nieminen
Posts: n/a
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

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:

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?
Reply With Quote
Marcel Müller
Posts: n/a
On 14.04.12 11.12, Juha Nieminen wrote:
> 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

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

Reply With Quote

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
Declaring a template class with two template params a friend in anon-template class A L C++ 1 08-25-2010 07:25 AM
r H2 deduce deduce template argument of a template class inheritingfrom a non template base? nguillot C++ 5 03-08-2009 05:56 PM
How to use the template member function of a template in the memberfunction of another template class? Peng Yu C++ 3 10-26-2008 03:51 PM
template template arguments: expected a class template, got `Component<T1, T2, T3> C++ 1 06-08-2007 07:10 AM
A parameterized class (i.e. template class / class template) is not a class? christopher diggins C++ 16 05-04-2005 12:26 AM