开发者

Statically Init a derived class

With c++, Is there a way to get a derived class to inherit its own static initializer? I am tryin开发者_JAVA技巧g to do something like the following:

class Base {

public:
        class StaticInit {
                public:
                virtual StaticInit() =0;
        };
};



class Derived: public Base {
  public:
        virtual StaticInit::StaticInit() {
           //do something with the derived class
        }
        static StaticInit init;
  }

static Derived::StaticInit init;

it would also be nice if I didn't have to define the init var in each derived class. I am currently redefining the StaticInit internal class in each derived class but it seems redundant.

Each derived class is a singleton, and I need the instance to be stored in a lookup table at program startup.


I use templates to do this, rather than inheritance - something like:

template <typename T>
struct StaticInit {
     StaticInit() {
         // do whatever with T
     }
};

in use:

static StaticInit <SomeClass> init;


Use the CRTP:

template <class D>
class Base {
public:
    class StaticInit {
    public:
        StaticInit() { D::initStatic(*this); }
    };
    static StaticInit init;
};

template <class D>
Base<D>::StaticInit init;

class Derived: public Base<Derived> {
public:
    initStatic(Base<Derived>::StaticInit& s) {
        // Do derived-specific initialisation on s.
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜