1

This question is hard to word, primarily because of the terms class instantiation vs. template instantiation. I have a template class that is full of static functions and members. Each specialization of this template needs to have some initialization done before it's first use.

My initial plan was to just give the template class a static initializer member, which will initialize the template class's static members during it's construction at dynamic initialization.

However, this isn't working. Unless I explicitly invoke code in the initializer class, the compiler won't generate any code or storage for it.

For example:

template<typename Tag>
class WorkerPool
{
    struct WorkerInitializer
    {
        void foo() { }
        WorkerInitializer() { WorkerPool<Tag>::start(); }
    };
    friend struct WorkerInitializer;
    static WorkerInitializer _initializer;

    static void start() { std::cout << "Started" << std::endl; }

public:
    static void async() { std::cout << "Async" << std::endl; }
};

template<typename T> typename WorkerPool<T>::WorkerInitializer 
WorkerPool<T>::_initializer;


struct GenericWorker { };
int main()
{
    WorkerPool<GenericWorker>::async();
}

The output is just 'Async'.

However, if I change it so that calling WorkerPool<T>::async() calls _initializer.foo(), then the initializer does get compiled and correctly constructed, as I would expect.

Why is the compiler refusing to generate code for my static member?

I've tested with Visual Studio 2010/2012, gcc, and clang, and all produce the same result; my static member is not constructed. This makes me think that the standard requires this behavior, but I'm having trouble understanding why this might be.

Collin Dauphinee
  • 13,664
  • 1
  • 40
  • 71

0 Answers0