开发者

Refer to derivative function

I have a base class and a few derivative. I have to 'register' some static function from each of them. Here is the example:

class Base
{
   // Some interface...
};

class Der1 : Base
{
   static void Do();
};
class Der2 : Base
{
   static void Do();
};

void processStatic()
{
   SomeFunc(Der1::Do);
   SomeFunc(Der2::Do);
}

As you see, SomeFunc receives function pointer. I w开发者_开发知识库ant to do that automatically with each new derivative class, is it possible? Maybe, predefine static function in Base class and register it there. But I think it's impossible, yes?


Maybe, this will be more easier to understand what do I want:

class Der1 : Base
{
   Der1() { SomeFunc(Der1::Do); }
   static void Do();
};
class Der2 : Base
{
   Der2() { SomeFunc(Der2::Do); }
   static void Do();
};


EDIT: Completely replacing previous answer due to clarified requirements.

You could use the CRTP to declare a specialized base class that does nothing more than call your registration function:

#include <iostream>
void SomeFunc(void(*fp)()) {
  (*fp)();
};

template <class D>
struct ExtraBass {
  ExtraBass() {
    static bool once;
    if(!once)
      SomeFunc(D::Do);
    once = true;
  }
};

struct Bass {
};

struct Drive : Bass, ExtraBass<Drive>  {
  static  void Do() { std::cout << "Drive::Do\n"; }
};

struct Deride : Bass , ExtraBass<Deride> {
  static  void Do() { std::cout << "Deride::Do\n"; }
};

int main() {
  Drive d1;
  Deride d2;
  Deride d3;
}


This is not an easy thing to do in C++, but I'm not saying it's impossible. If all you need is a list of subclass names, these answers might help:

Somehow register my classes in a list

c++ List of classes without initializing them for use of static functions

Seems either macro magic or boost mpl is your tool of choice.


I just wondering, if you did something like

void SomeFunc(void (*doFunc)())
{ 
   doFunc();
}

template <class T> int Register()
{
    SomeFunc(T::Do);
    return 0;
}

template <class T> class Base
{
   static int _i;
};

template <class T> int Base<T>::_i =  Register<T>();

class Derived : Base<Derived>
{
   public:
   static void Do() {  }
};
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜