c++ - std::map 可以包含对构造函数的引用吗?

标签 c++ c++11 stdmap std-function

有没有办法从 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/

相关文章:

osx 和 windows 中的 C++ 转义字符差异?

c++ - 具有 C++11 和线程支持的 Visual Express C++

c++ - 什么时候使用 std::unordered_map::emplace_hint?

c++ - 如何调用指向函数指针的指针?

c++ - std::map 中的最后一个键

c++ - 为什么我不能将 unique_ptr 转换为赋值中的原始指针?

c++ - 将无符号短裤数组转换为无符号字符数组

c++ - 如何声明在模板中使用的常量?

c++ - 这张 map 有什么问题?

C++ 静态函数和线程安全