有没有办法从 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++ 中获取构造函数的地址。有没有一种优雅的方式来完成我想在这里做的事情?
最佳答案
根据 C++ 标准,您不能获取构造函数的地址 (C++98/03 的第 12.1.12 节和 C++11 的第 12.1.10 节):
Constructors - The address of a constructor shall not be taken.
对于这个问题,典型的解决方案是创建特定的工厂/方法来创建对象。
关于c++ - std::map 可以包含对构造函数的引用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32488600/