6

Possible Duplicate:
(static initialization/template instantiation) problems with factory pattern
trying to force static object initialization

EDIT: There is a duplicate of this but I'll leave this up as I personally had trouble finding it. In addition here's the answer that helped me:

https://stackoverflow.com/a/2852234/673730

Assume the following class:

template<class X>
struct A
{
   static bool x;
   static bool foo()
   {
      cout << "here";
      return true;
   }
};

template<class X>
bool A<X>::x = A<X>::foo();

I would have assumed that when I specialize A, the static field x would get initialized. However, the following:

A<int> a;
//no output

doesn't result in a call to foo. If I try to access the member, the behavior is as expected:

A<int> a;
bool b = a.x;
//output: here

EDIT: How can I make sure A::x is initialized without accessing it?

Community
  • 1
  • 1
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625

2 Answers2

12

If a template is implicitly specialised by virtue of being instantiated, then only those members that are actually referred to are instantiated.

Contrast this with explicit class template instantiation (template struct A<int>;), which instantiates and creates code for all members. (You can also instantiate only specific members individually: template bool A<int>::x;.)

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
1

This think is the reference(14.7.1.2) :

Unless a member of a class template or a member template has been explicitly instantiated or explicitly specialized, the specialization of the member is implicitly instantiated when the specialization is referenced in a context that requires the member definition to exist; in particular, the initialization (and any associated side-effects) of a static data member does not occur unless the static data member is itself used in a way that requires the definition of the static data member to exist.

template<class X, bool y>
struct A
{
    static cosnt bool x = y;
    static bool foo()
    {
       cout << "here";
       return true;
    }
 };
ManiP
  • 713
  • 2
  • 8
  • 19