涉及枚举 class 和宏扩展的代码片段的含义

meaning of code snippet involving enum class and macro expansion

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

我了解宏扩展和枚举的基础知识class。 我了解到带有参数 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};

我说得对吗?

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

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

然后它定义实用函数:

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