姬長信(Redy)

现代C 11 / C 14 / C 17和未来C 20中的字符串


与所有其他类似问题相反,这个问题是关于使用新的C功能.

> 2008 Is there a simple way to convert C++ enum to string?
> 2008 Easy way to use variables of enum types as string in C?
> 2008 How to easily map c++ enums to strings
> 2008 Making something both a C identifier and a string?
> 2008 Is there a simple script to convert C++ enum to string?
> 2009 How to use enums as flags in C++?
> 2011 How to convert an enum type variable to a string?
> 2011 Enum to String C++
> 2011 How to convert an enum type variable to a string?
> 2012 How to convert enum names to string in c
> 2013 Stringifying an conditionally compiled enum in C

看了很多答案后,我还没找到:

>使用C++11,C++14C++17新功能的优雅方式
>或者在Boost准备使用的东西
>计划于C++20计划一些事情

一个例子通常比长期解释更好.
您可以在Coliru编译并运行此代码段.
(Another former example也有)

#include 
#include 

struct MyClass
{
    enum class MyEnum : char {
        AAA = -8,
        BBB = '8',
        CCC = AAA + BBB
    };
};

// Replace magic() by some faster compile-time generated code
// (you're allowed to replace the return type with std::string
// if that's easier for you)
const char* magic (MyClass::MyEnum e)
{
    const std::map MyEnumStrings {
        { MyClass::MyEnum::AAA, "MyClass::MyEnum::AAA" },
        { MyClass::MyEnum::BBB, "MyClass::MyEnum::BBB" },
        { MyClass::MyEnum::CCC, "MyClass::MyEnum::CCC" }
    };
    auto   it  = MyEnumStrings.find(e);
    return it == MyEnumStrings.end() ? "Out of range" : it->second;
}

int main()
{
   std::cout 

约束

>请不要重复other answersbasic link的宝贵重复.
>请避免膨胀的基于宏的答案,或尝试尽可能减少#define开销.
>请不要手动枚举 – >字符串映射.

很高兴有

>支持从不同于零的数字开始的枚举值
>支持负枚举值
>支持碎片枚举值
>支持类枚举(C 11)
>支持类枚举:任何允许的 (C 11)
>编译时(不是运行时)转换为字符串,
或者至少在运行时快速执行(例如std :: map不是一个好主意……)
> constexpr(C 11,在C 14中放松)
> noexcept(C 11)
>片段C 14 / C 17友好
> C State of the art

一个可能的想法是使用C编译器功能在编译时使用基于可变参数模板类和constexpr函数的元编程技巧生成C代码…