The "inlineness" of template class variables

Discussion in 'C++' started by Juha Nieminen, Apr 14, 2012.

  1. 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?
     
    Juha Nieminen, Apr 14, 2012
    #1
    1. Advertising

  2. 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
    linker.

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


    Marcel
     
    Marcel Müller, Apr 14, 2012
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Matt Graham
    Replies:
    0
    Views:
    565
    Matt Graham
    Jul 21, 2003
  2. christopher diggins
    Replies:
    16
    Views:
    756
    Pete Becker
    May 4, 2005
  3. Replies:
    1
    Views:
    2,113
    Gianni Mariani
    Jun 8, 2007
  4. nguillot
    Replies:
    5
    Views:
    532
  5. A L
    Replies:
    1
    Views:
    511
    Alf P. Steinbach /Usenet
    Aug 25, 2010
Loading...

Share This Page