Template static variable
Asked Answered
C

3

64

I can't understand, why if we define static variable of usual (non-template) class in header, we have linker error, but in case of templates all works fine and moreover we will have single instance of static variable among all translation units:

It's template header (template.h):

// template.h
template<typename T>
class Templ {
public:
  static int templStatic;
};

template<typename T> Templ<T>::templStatic = 0;

It's first unit using template (unit1.cpp)

// unit1.cpp
#include "template.h"

int method1() {
  return Templ<void>::templStatic++;
}

Second unit here (unit2.cpp):

// unit2.cpp
#include "template.h"
int method2() {
  return Templ<void>::templStatic++;
}

And, finally, main.cpp:

// main.cpp
#include <iostream>
int method1();
int method2();

int main(int argc, char** argv) {
  std::cout << method1() << std::endl;
  std::cout << method2() << std::endl;
}

After compilling, linking and executing this code, we will have following output:

0
1

So, why in case of templates all works fine (and as expected) ? How compiler or linker handle this (we can compile each .cpp file in separated calling of compiler, and then link them with caling to linker, so compiler and linker don't "see" all .cpp files at same time) ?

PS: My compiler: msvcpp 9 (but checked on mingw too)

Carruthers answered 12/10, 2009 at 10:39 Comment(2)
It would be more useful if you showed us the code that doesn't work.Dietary
I suppose that code that doesn't work is the one where you define a variable in a header which gets included in more than one file (not externed), which results in a naming collision.Uzia
F
69

It's because the definition of the static data member is itself a template. Allowing this is necessary for the same reason you are allowed to have a function template that's not inline multiple times in a program. You need the template to generate the resulting entity (say, a function, or a static data member). If you wouldn't be allowed to put the definition of a static data member, how would you instantiate the following

template<typename T>
struct F {
  static int const value;
};

template<typename T>
int const F<T>::value = sizeof(T);

It's not known what T is - the Standard says the definition outside the class template is a template definition, in which the parameters are inherited from its class template owner.


I've made some experiment with GCC. In the following, we have one implicit instantiation of F<float>::value, and one explicit specialization of F<char>::value which has to be defined in a .cpp file to not cause duplicated symbol errors when included multiple times.

// Translation Unit 1
template<typename T>
struct F {
  static int value; 
};

template<typename T>
int F<T>::value = sizeof(T);

// this would belong into a .cpp file
template<> int F<char>::value = 2;

// this implicitly instantiates F<float>::value
int test = F<float>::value;

int main() { }

The second translation unit contains just another implicit instantiation of the same static data member

template<typename T>
struct F {
  static int value; 
};

template<typename T>
int F<T>::value = sizeof(T);

int test1 = F<float>::value;

Here is what we get with GCC - it makes each implicit instantiation into a weak symbols and sticks it into its own section here. Weak symbols will not cause errors when there exist multiple of them at link time. Instead, the linker will choose one instance, and discards the other ones assuming all of them are the same

objdump -Ct main1.o # =>
# cut down to the important ones
00000000 l    df *ABS*  00000000 main1.cpp
0000000a l     F .text  0000001e __static_initialization_and_destruction_0(int, int)
00000000 l    d  .data._ZN1FIfE5valueE  00000000 .data._ZN1FIfE5valueE
00000028 l     F .text  0000001c global constructors keyed to _ZN1FIcE5valueE
00000000 g     O .data  00000004 F<char>::value
00000000 g     O .bss   00000004 test
00000000 g     F .text  0000000a main
00000000  w    O .data._ZN1FIfE5valueE  00000004 F<float>::value

So as we can see F<float>::value is a weak symbol which means the linker can see multiple of these at link time. test, main and F<char>::value are global (non-weak) symbols. Linking main1.o and main2.o together, we see in the map output (-Wl,-M) the following

# (mangled name)
.data._ZN1FIfE5valueE
    0x080497ac        0x4 main1.o                                             
    0x080497ac                F<float>::value

This indicates that actually it drops all except one instance.

Foredeck answered 12/10, 2009 at 10:47 Comment(1)
Ok. But how linker, which see two "template<typename T> Templ<T>::templStatic = 0;" definitions (in unit1.cpp and unit2.cpp) handle this situation ? Is object files has some C++ - specific meta information, which can say to linker, that one definition can be ignored (and, as result we haven't "multiple definitions" linker error)?Carruthers
W
3

There is solution, you can create a parent class and put the static variable in it, then make your template class inherit it privately, here's an example:

class Parent
{
protected: 
    static long count;
};

long Parent::count = 0;

template<typename T>
class TemplateClass: private Parent
{
private: 
    int mKey;
public:
    TemplateClass():mKey(count++){}
    long getKey(){return mKey;}
}

int main()
{
    TemplateClass<int> obj1;
    TemplateClass<double> obj2;

    std::cout<<"Object 1 key is: "<<obj1.getKey()<<std::endl;
    std::cout<<"Object 2 key is: "<<obj2.getKey()<<std::endl;

    return 0;
}

Output will be:

Object 1 key is: 0 
Object 2 key is: 1
Wolcott answered 18/12, 2016 at 16:0 Comment(2)
you should make clear in your response, that all TemplateClass instances share the same static count. In that your answer differs to the templated static member variable in the accepted answer: in that case, the static member is shared per template argument (i.e. each instantiation of the template with the same template type)Myxomycete
@Myxomycete that's the expected behaviour though, so I do not think there's a need to make it clear?Potential
S
1

It's because template code is not source code; it's instructions on how to write source code.

The non-template static variable is actual source code, and the compiler will attempt to do exactly what you say by including something in twice. Hence, you have to initialize the static variable in a .cpp file, and only reference it in the .h file describing the class. It's equivalent to a global variable declared through extern.

When the compiler sees

template<class T> Templ{...};

it does nothing except make a note that the template exists. As far as it is concerned, there is no source code associated with Templ. The first time you actually refer to

Templ<int> Instance

the compiler looks at all the template<> code associated with Templ and uses it to construct a .h and a .cpp file (which exists only for the duration of compilation). Those files might look like this:

Temple_int.h
class Templ_int{
  public:
  static int templStatic;
};

Templ_int.cpp
#include "Templ_int.h"
Templ_int::templStatic = 0;

And every

Templ<int>

becomes a Templ_int. Thus, the source code to initialize the static variable only exists once, in a .cpp file created by the compiler. (Obviously, the actual compiler-specific implementation of this process would be robust against creating a class with a similar name to the template, etc.)

Shortsighted answered 10/2, 2019 at 4:35 Comment(1)
Why compiler is throwing an error if we don't initialize the static variables.I tried to remove the following lines Templ_int::templStatic = 0;Trilingual

© 2022 - 2024 — McMap. All rights reserved.