【发布时间】:2015-09-09 20:29:21
【问题描述】:
有没有办法从 std::map 指向构造函数?我想使用我希望在#if 0 中使用的代码执行以下操作,但我似乎无法让它工作:
#include <map>
#include <functional>
using namespace std;
class Base { };
class A : public Base { };
class B : public Base { };
enum class Type { A, B, };
#if 0
using type_map_t = std::map<Type, std::function<Base*()>>;
type_map_t type_map = {
{Type::A, &A::A},
{Type::B, &B::B},
};
#endif
Base*
getBase(Type t)
{
#if 0
auto constructor = type_map[t];
return constructor();
#else
switch(t)
{
case Type::A:
return new A();
case Type::B:
return new B();
}
#endif
}
int
main(int argc, char *argv[])
{
Base *base = getBase(Type::A);
return 0;
}
与其在 getBase 中使用 switch 语句,我宁愿让地图指示每种类型调用的构造函数。
std::function 想到了如何做到这一点,但似乎不可能在 C++ 中获取构造函数的地址。有没有一种优雅的方式来完成我想要在这里做的事情?
【问题讨论】:
-
这叫做工厂模式
-
适用于您的用例的工厂模式的描述:stackoverflow.com/a/954565/956880
标签: c++ c++11 stdmap std-function