你好,我目前正在学习 C++,我想知道是否有可能制作一个由派生类构造函数组成的指针函数数组。
让我们看这个例子: 假设我有抽象类 A;
Class A
{
public:
A(const std::string& name):_name(name){};
void doSomething(void) = 0;//void
private:
const std::string _name;
}
然后是A的以下派生类:
Class B: public A
{
public:
B(const std::string& name):A(name);
void doSomething(void) = 0;//void
A* factory(void) {return new B};
}
Class C: public A
{
public:
C(const std::string& name):A(name);
void doSomething(void) = 0;//void
A* factory(void) {return new C};
}
它们都有一个公开的工厂成员函数,以便其他类可以在需要时创建它们。 现在让我们添加另一个类来创建指向构造函数的指针
typedef struct obj
{
std::string name;
A* (A::*make)(const std::string& name);
} obj;
class Caller
{
public:
Caller(const std::string& name)
{
obj[0].name = "lol"
obj[0].make = B::factory;
obj[1].name = "lolx"
obj[1].make = C::factory;
}
A* createObj(const std::string& name)
{
int i = -1;
while (++i < 2)
{
if (obj.name == name)
return (obj -> make());
}
return (NULL);
}
private:
obj _obj[2];
}
我知道这不正确,因为我在我的电脑上尝试过并且有错误,但是可以做我刚刚向你展示的事情吗? 总而言之,我想创建一个类,它有一个指向派生类的构造函数函数的指针数组,这样如果作为参数传递给 Caller 类的名称与 obj 数组中的名称匹配,我可以使用它们的构造函数。
您的问题的另一种解决方案是结合使用 std::function 和 std::map.
例如
//factory function object, signature: A* func_id(const std::string&)
using func = std::function<A*(const std::string&)>;
//function map declaration
std::map<
std::string, //key: the lookup string
func //value: function object pointing to the factory method (ctor)
> func_map;
//function registration
//------------------------------
//register B factory
//here a lambda is used, could be also any function address
func_map["class_B"] = [](const std::string& name) {
return reinterpret_cast<A*>( new B{name} );
};
//register C factory
//here a lambda is used, could be also any function address
func_map["class_C"] = [](const std::string& name) {
return reinterpret_cast<A*>( new C{name} );
};
//usage:
//------------------------------
//for new B
auto b = std::shared_ptr<A>{ //result as shared_ptr instead of raw pointer
//lookup "class_B" and call ctor of B with the parameter "name_B"
func_map["class_B"]("name_B")
};
//b->doSomething();
//for new C
auto c = std::shared_ptr<A>{ //result as shared_ptr instead of raw pointer
//lookup "class_C" and call ctor of C with the parameter "name_C"
func_map["class_C"]("name_C")
};
//c->doSomething();
优势:
参考: