如何传递一个指向构造函数的函数指针? [英] How to pass a function pointer that points to constructor?

查看:778
本文介绍了如何传递一个指向构造函数的函数指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在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
};

对于具有静态类成员基准的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.

推荐答案

你不能接受构造函数的地址(C ++ 98 Standard 12.1 / 12 Constructors - 12.1-12 Constructors -

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;
}

这篇关于如何传递一个指向构造函数的函数指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆