将C 枚举类成员拉入全局名称空间

Pulling C++ Enum Class Members Into the Global Namespace

本文关键字:全局 空间 枚举 成员      更新时间:2023-10-16

是否有using指令将enum class的成员直接导入汇编单元的全局名称空间?

我们有:

enum Lexeme {....lots of names...};
bool Matches(int lookAhead, Lexeme lxm);

这是有风险的,因为用户经常忘记Matches的第一个参数表示"匹配"并写入:

if (Matches(ADD,SUB)) ...

C 编译器非常高兴以ADD为int。

所以我尝试使Lexeme enum class

enum class Lexeme { ...}

这会遇到错误。但是现在我的问题是使用Lexeme常数的所有代码都必须编写enum class名称:

if (Matches(Lexeme::ADD,Lexeme::SUB)) ...

是否有using指令或其他技巧将所有Lexeme::*名称都拉到当前范围中?请注意,大多数令牌都在课堂中使用(我得到适当资格的常数是enum class的安全机制之一(。

也许一个更好的计划是将Matches更改为MatchesAt或其他内容,以避免问题?但是我想知道C 和C XX的规则。

我尝试的是:

这是相关的,但没有解决所需的enum class前缀。

我也尝试了类似using foo::bar::Lexeme的东西;但是可惜无济于事。

您可以使整数包装类别不能转换为其他任何东西,并从中制成一些常数。

struct Lexeme
{
   private: int m_value;
   public: explicit constexpr Lexeme(int value) noexcept
   : m_value{value}
   {}
};
inline constexpr Lexeme const ADD{1};
inline constexpr Lexeme const SUB{2};

超载某些操作员的好主意,至少相等,少于。

在另一个音符上,避免每次创建Lexeme::的方法只是创建一个较短的别名:

enum class Lexeme { /* lotsa names */ };
using L = Lexeme;
if (Matches(3, L::SUB)) //...

如果只有一个或两个文件广泛使用这些值,并且其他用途稀疏。我只需要使用类似的解决方案,其中我有一个参数类,该类别从XML中读取内容。我有一个enum class ElementType { INTEGER, BOOLEAN, /* etc*/ }和一个解析基础架构。在解析器文件中,我有:

using ET = ElementType;
template<ET et>
struct parser;
// Specializations for each ElementType
template<>
struct parser<ET::INTEGER> {
    using type = int;
    int parseSingle(const string& s) // ...
}

虽然在此文件之外,我只有几个用法的ElementType ::*常数,并且我使用了枚举类的全名。如果这变得太大了,没有什么可以阻止我对其他文件的别名。