【问题标题】:Enum class to string枚举类到字符串
【发布时间】:2021-11-16 19:57:59
【问题描述】:

我有一个带有 switch 案例的解决方案,但有很多案例,所以 clang-tidy 对该功能发出警告。我的动机是减小函数的大小。有什么办法可以减少函数的大小。

【问题讨论】:

    标签: string switch-statement alternate enum-class


    【解决方案1】:

    由于enum class可以作为std::map的key,你可以使用map来保持枚举字符串的关系,像这样:

    enum class test_enum { first, second, third };
    
    const char* to_string(test_enum val) {
        static const std::map<test_enum,const char*> dict = {
            { test_enum::first, "first" },
            { test_enum::second, "second" },
            { test_enum::third, "third" }
        };
        
        auto tmp = dict.find(val);
        return (tmp != dict.end()) ? tmp->second : "<unknown>";
    }
    

    C++没有反射,所以map不能自动填充;但是,使用特定于编译器的扩展(例如,像 GCC 的 __PRETTY_FUNCTION__ 扩展)可以完成,例如比如magic_enum library

    【讨论】:

      猜你喜欢
      • 2014-07-23
      • 2011-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多