c++ - 是否可以将 int(enum) 映射到类型

标签 c++ dictionary

假设我有这个简化的示例:
我有一些代码可以对类进行序列化和反序列化... 第一个字节是编码类类型的枚举(它们都继承自相同的基类).. 例如。

    Color* c;
    auto classType == read_byte(buffer);
    switch (classType)
    case eBlue:
    {
       c = new Blue(buffer);
    }
    case eGray:
    {
       c = new Gray(buffer)
    }

//...

有什么办法可以有一个从枚举到类型的映射,这样我就可以替换开关

c = new enum2Type(buffer);

编辑 ofc 我永远不会使用原始 ptr IRL。:)

最佳答案

template<typename T>
T* makeColor(Buffer const& buffer)
{
    return new T(buffer);
}

...

std::map<ColerEnum, Color* (*)(Buffer const&)> m;
m[grayEnum] = makeColor<Gray>;

...

Color* c = m[typeByte](buffer);

关于c++ - 是否可以将 int(enum) 映射到类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16691214/

相关文章:

c++ - 是否有一个 API 可以在 iOS 上运行以更改现有视频的每秒帧数?

Scripting.Dictionary Lookup-add-if-not-present 只有一键搜索?

python - 如何在字典理解中写两个其他条件

python - 如何反向索引 Counter 并将其转换为 defaultdict? Python

ios - swift 错误 : Reference to generic type Dictionary requires arguments in <. ..>

c++ - 智能指针的优缺点

c++ - 如何找到机器代码指令的结尾以增加指令指针

c++ - InternetReadFile 只读取 10kb

c++ - 模板化检查是否存在类成员函数?

python - 为什么我不能得到这个简单的 Python 字典的键/值对?