How to pass a function pointer that points to constructor?(如何传递指向构造函数的函数指针?)
问题描述
我正致力于在 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;
}
这篇关于如何传递指向构造函数的函数指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何传递指向构造函数的函数指针?


- 如何对自定义类的向量使用std::find()? 2022-11-07
- STL 中有 dereference_iterator 吗? 2022-01-01
- 近似搜索的工作原理 2021-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 静态初始化顺序失败 2022-01-01
- C++ 协变模板 2021-01-01
- 从python回调到c++的选项 2022-11-16
- Stroustrup 的 Simple_window.h 2022-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01