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