#include <iostream>
template <typename T>
class Temp {
public:
static Temp temp;
Temp() { std::cout << "hi!"; }
};
// Definition.
template <typename T>
Temp<T> Temp<T>::temp;
I created a simple template class. I thought that instantiating Temp
object is enough to construct static temp
in Temp
.
int main() {
Temp<int> t;
}
But this only returned one "hi!".
Whereas if I explicitly reference the temp
,
int main() {
Temp<int> t;
Temp<int>::temp;
}
it printed "hi!" two times and I could confirm that the static object was created during its usual initialization time (before calling main). Whats the criteria on compiler to omit the construction of static object? Also how do I enforce it other than referencing it?