0

As a static class member variable, it will be instantiated at the early time of the program. How to make this happens on a function? My example is that I have a factory class, which need register types before using it. And I'd like the registration happens earlier than I use it to create an object.

user1899020
  • 12,499
  • 17
  • 70
  • 145
  • 4
    You can initialize a static by calling a function (`MyClass::initialized = register()`). Or you can try this - http://stackoverflow.com/a/10333643/673730 – Luchian Grigore Sep 15 '13 at 20:29

1 Answers1

3

Typically we shall use the constructor of a "registration class" type to do this.

The "trick" is to recall that, when you initialise a file-static object you are — albeit indirectly — calling a function. It's the constructor for that object. You can use that.

registration.h

template <typename T>
class Registration
{
   Registration();
};

#include <registration.ipp>

registration.ipp

template <typename T>
Registration::Registration()
{
   //!! Do your work with `T` here.
}

myClass.h

class MyClass
{
public:
   MyClass();
};

myClass.cpp

#include "myClass.h"
#include "registration.h"

// Static; instantiated once, before `main` runs
Registration<MyClass> reg;

MyClass::MyClass() {}
// ...
Lightness Races in Orbit
  • 369,052
  • 73
  • 620
  • 1,021