Implicit constructor / inherited constructor and custom constructor with different behavior

I have a piece of code that automatically runs a function for a class when the application starts:

template<class T> struct RegClass;

template <typename T>
struct AutoRegister {
  AutoRegister() { (void)&ourRegisterer; }
private:
  static RegClass<T> ourRegisterer;
};

template <typename T>
RegClass<T> AutoRegister<T>::ourRegisterer;

template<class T>
struct RegClass {
  RegClass() {
    printf("registering\n");
  }
};

      

To use it for a class, I simply inherit from AutoRegister<T>

:

struct Foo : AutoRegister<Foo>{
  Foo() {}
};

      

In this example, the application will print out "registration" without even creating an object of the type Foo

. http://coliru.stacked-crooked.com/a/fc1678b1a18e8971

However, it seems that defining this behavior requires defining a constructor for Foo

. Implicit constructor or base class constructor inheritance is not enough: http://coliru.stacked-crooked.com/a/a54c53afe2724cdf

Thanks for the link What are the rules for initializing a static class variable?

I looked at constructor inheritance and they have the same "defined-when-used" rule as implicit constructors, which explains that this part too

+3


source to share





All Articles