如何传递指向构造函数的函数指针?

我正致力于在 C++ 中实现反射机制.我的代码中的所有对象都是 Object(我自己的泛型类型)的子类,其中包含一个 Class 类型的静态成员数据.

I'm working on implementing a reflection mechanism in C++. All objects within my code are a subclass of Object(my own generic type) that contain a static member datum of type Class.

class Class{
public:
   Class(const std::string &n, Object *(*c)());
protected:
   std::string name;     // Name for subclass
   Object *(*create)();  // Pointer to creation function for subclass
};

对于具有静态 Class 成员数据的 Object 的任何子类,我希望能够使用指向该子类的构造函数的指针来初始化create".

For any subclass of Object with a static Class member datum, I want to be able to initialize 'create' with a pointer to the constructor of that subclass.

推荐答案

You cannot take the address of a constructor (C++98 Standard 12.1/12 Constructors - "12.1-12 Constructors - "The address of a constructor shall not被带走.")

You cannot take the address of a constructor (C++98 Standard 12.1/12 Constructors - "12.1-12 Constructors - "The address of a constructor shall not be taken.")

最好的办法是有一个工厂函数/方法来创建Object并传递工厂地址:

Your best bet is to have a factory function/method that creates the Object and pass the address of the factory:

class Object;

class Class{
public:
   Class(const std::string &n, Object *(*c)()) : name(n), create(c) {};
protected:
   std::string name;     // Name for subclass
   Object *(*create)();  // Pointer to creation function for subclass
};

class Object {};

Object* ObjectFactory()
{
    return new Object;
}



int main(int argc, char**argv)
{
    Class foo( "myFoo", ObjectFactory);

    return 0;
}

相关文章