【提高效率】C++使用map替代传统switch case

switch case示例

c 复制代码
enum class ENTestType
{
    first = 1,
    second,
    third,
    forth
};

class Test
{
public:
    void testFun(ENTestType type)
    {
        switch (type)
        {
        case ENTestType::first:
            std::cout << "first" << std::endl;
            break;
        case ENTestType::second:
            std::cout << "first" << std::endl;
            break;
        case ENTestType::third:
            std::cout << "third" << std::endl;
            break;
        case ENTestType::forth:
            std::cout << "forth" << std::endl;
            break;
        default:
            break;
        }
    }
};

int main()
{
    auto t = std::make_unique<Test>();
    t->testFun(ENTestType::first);
    return 0;
}

使用map替代switch:

cpp 复制代码
class Test
{
public:
    Test()
    {
        _testMap[ENTestType::first] = []{
            std::cout << "first" << std::endl;
        };
        _testMap[ENTestType::second] = []{
            std::cout << "second" << std::endl;
        };
        _testMap[ENTestType::third] = []{
            std::cout << "third" << std::endl;
        };
        _testMap[ENTestType::forth] = []{
            std::cout << "forth" << std::endl;
        };
    }
public:
    std::map<ENTestType, std::function<void()>> _testMap;
};

int main()
{
    auto t = std::make_unique<Test>();
    t->_testMap[ENTestType::first]();
    return 0;
}
相关推荐
GISer_Jing4 分钟前
OSG底层从Texture读取Image实现:readImageFromCurrentTexture
前端·c++·3d
!chen8 分钟前
CPP 学习笔记 语法总结
c++·笔记·学习
杨筱毅12 分钟前
【穿越Effective C++】条款17:以独立语句将newed对象置入智能指针——异常安全的智能指针初始化
c++·effective c++
moiumxf0278q1 小时前
C++中智能指针是如何工作的?
java·jvm·c++
似水এ᭄往昔1 小时前
【C++】--模板进阶
开发语言·c++
AA陈超2 小时前
虚幻引擎5 GAS开发俯视角RPG游戏 P07-11 实现自动运行
c++·游戏·ue5·游戏引擎·虚幻
DARLING Zero two♡2 小时前
【优选算法】LinkedList-Concatenate:链表的算法之契
数据结构·c++·算法·链表
yolo_guo2 小时前
opencv 学习: 07 使用迭代器 (iterator) 遍历像素
linux·c++·opencv
mjhcsp3 小时前
C++ 高精度计算:突破数据类型限制的实现与应用
开发语言·c++·算法·高精度
lixinnnn.3 小时前
C++: map和set
开发语言·c++