可以将int(枚举)映射到类型 [英] Is it possible to map int(enum) to type

查看:101
本文介绍了可以将int(枚举)映射到类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我说这个简化的例子:

我有一些代码来执行序列化和反序列化一个类...
第一个字节是枚举类型类型(他们都继承自相同基数)..
eg。

lets say I have this simplified example:
I have some code that does serialization and deserialization of a class... first byte is enum that encodes class type(they all inherit from same base).. eg.

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

//...

有从枚举到类型的映射的任何方式,所以我可以替换switch



is there any way to have a map from enum to type so I can replace switch

c = new enum2Type(buffer);

edit ofc我永远不会使用raw ptr IRL。:)

edit ofc I would never use raw 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);

这篇关于可以将int(枚举)映射到类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆