2
// A.h
class A {
public:
  static int a;
};
int A::a = 0;

If I try to include A.h in multiple .cpp files, link would fail with multiple definition of A::a. I think this makes sense because each .obj file contains A::a

However, I could use a template,

// A.h
template<class T>
class A {
public:
  static T a;
};
template<class T>
T A<T>::a = 0;

I can now include A.h in multiple .cpp files and also I can assign the value A<int>::a = 100; in one .cpp file and get the same value in another one with A<int>::a.

  • When does template make such difference?
  • Is there only 1 copy of this static variable? Which .obj will keep this variable?
  • Is the constructor called only once? If the initial value is different, which one wins?
woodings
  • 7,503
  • 5
  • 34
  • 52

2 Answers2

1

When does template make such difference?

Always. I suppose I don't understand the question.

Is there only 1 copy of this static variable?

Only one copy in the final program for each distinct type T the template was instantiated with.

Which .obj will keep this variable?

All of them that were generated from translation units where the template was instantiated. The linker then chooses one and discards all others.

Is the constructor called only once?

Once for each specialization.

If the initial value is different, which one wins?

That would be a violation of the One Definition Rule. Such a program would be ill-formed, no diagnostic required.

Igor Tandetnik
  • 50,461
  • 4
  • 56
  • 85
  • 1
    I understand the code in the example is against the best practice. But I was trying to understand how link works with the code like this. – woodings Aug 30 '13 at 05:33
-1

Why not define static member in the souce file that implements the class A? Then you should be able to include A.h in multiple source files w/o problem.

// A.h
class A {
public:
  static int a;
};

// A.cpp
int A::a = 0;
Eric Z
  • 14,327
  • 7
  • 45
  • 69