【问题标题】:meaning of code snippet involving enum class and macro expansion涉及枚举类和宏扩展的代码片段的含义
【发布时间】:2019-09-05 20:42:39
【问题描述】:

我在 C++ 中遇到以下代码。我是该语言的新手,不熟悉语法。

我了解宏扩展和枚举类的基础知识。 我了解到带有参数x1,x2,...,xn 的宏etokenize 将被#x1,#x2,...#xn 替换。函数s_tolowerstd::string 中的每个字符更改为小写。

#define DECL_ENUM_FUNCS(e)        inline const char* enum2str(e e1){ return e##__str__[static_cast<int>(e1)]; } \
                                inline bool str2enum(const std::string& s,e& e1){for(int i=0;i<static_cast<int>(e::End);i++){ if( s==e##__str__[i] ){e1=static_cast<e>(i);return true;} } e1=e::End; return false; } \
                                inline bool str2enumI(const std::string& s,e& e1){for(int i=0;i<static_cast<int>(e::End);i++){ if( s_tolower(s)==s_tolower(e##__str__[i]) ){e1=static_cast<e>(i);return true;} } e1=e::End; return false; } \
                                inline std::ostream& operator<<(std::ostream& o, e const & in_) { o << e##__str__[static_cast<int>(in_)]; return o; }

#define DECL_ENUM(e,x1,...) enum class e : int { x1=0, __VA_ARGS__, End }; const char e##__str__[][256] = {#x1, etokenize(__VA_ARGS__), "Invalid"}; DECL_ENUM_FUNCS(e)

我的问题是关于一般语法,而不是所涉及函数的细节。例如,为什么替换列表中有 4 个内联函数? 最后一行在做什么?如果我的问题写得不好,我深表歉意,因为我还是个初学者。

我猜

DECL_ENUM(type, a,b,c) 

将与

相同
enum class type { a, b, c};

我说的对吗?

【问题讨论】:

    标签: c++ enum-class


    【解决方案1】:

    不,对于enum class 部分,您错过了两件事:

    • 类型设置为int
    • 并在末尾添加End 值。

    然后它定义实用函数:

    • 将枚举值转换为其字符串表示:type::a --> 'a'
    • 查找与字符串对应的枚举值:'a' --> type::a
    • 忽略大小写同上:'A' --> type::a
    • 将文本表示打印到std::ostreamstd::cout &lt;&lt; type::a

    【讨论】:

    • 它只指定枚举的后备存储,它不会改变它的类型。 int 是默认的,所以有点热情。 “最后一个”枚举成员很常见,有助于实现值检查。
    • 顺便说一下,‘e__str__[i]’看起来是一个非标准的编译器特定的扩展。出于好奇,您的工具链是什么?
    • e__str__ 是一个多维数组,就像int a[][2] = {{1,2},{3,4},{5,6}}; 一样。没有特定的编译器。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-25
    • 1970-01-01
    • 2014-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多