【提高效率】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;
}
相关推荐
疯狂的喵4 小时前
C++编译期多态实现
开发语言·c++·算法
2301_765703144 小时前
C++中的协程编程
开发语言·c++·算法
m0_748708054 小时前
实时数据压缩库
开发语言·c++·算法
小魏每天都学习5 小时前
【算法——c/c++]
c语言·c++·算法
m0_748233176 小时前
30秒掌握C++核心精髓
开发语言·c++
风清扬_jd7 小时前
libtorrent-rasterbar-2.0.11编译说明
c++·windows·p2p
u0109272717 小时前
C++中的RAII技术深入
开发语言·c++·算法
彷徨而立7 小时前
【C/C++】strerror、GetLastError 和 errno 的含义和区别?
c语言·c++
誰能久伴不乏7 小时前
【Qt实战】工业级多线程串口通信:从底层协议设计到完美收发闭环
linux·c++·qt
2401_832131958 小时前
模板错误消息优化
开发语言·c++·算法