0

I’m having a solution with switch cases but there are many cases so clang-tidy is giving warning for that function. My motive is to decrease the size of function. Is there any way that we can do to decrease size of function.

1 Answers1

0

As enum class can be used as key for std::map, You can use the map to keep relation of enum <-> string, like this:

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++ has no reflection, so map cannot be filled automatically; however, using compiler-specific extensions (e.g. like __PRETTY_FUNCTION__ extension for GCC) it can be done, e.g. like in magic_enum library

raku99
  • 57
  • 2