Is there a way to point to a constructor from a std::map? I'd like to do the following, with the code I desire to use in #if 0
, but I can't seem to get this to work:
#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;
}
Rather than have a switch statement in getBase, I'd rather have the map indicate what constructor gets called for each type.
std::function comes to mind for how to do this, but it doesn't seem possible to get the address of a constructor in C++. Is there an elegant way to accomplish what I want to do here?