簡體   English   中英

將C ++枚舉類成員放入全局命名空間

[英]Pulling C++ Enum Class Members Into the Global Namespace

是否有一個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)) //...

如果只有一個或兩個文件廣泛使用這些值,而其他用途很少,則此方法效果很好。 我只是不得不使用類似的解決方案,在該解決方案中,我有一個Parameter類,該類從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 :: *常量,並且使用了枚舉類的全名。 萬一這成為一個沉重的負擔,沒有什么可以阻止我將該別名添加到其他文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM