将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)) //...
如果只有一个或两个文件广泛使用这些值,并且其他用途稀疏。我只需要使用类似的解决方案,其中我有一个参数类,该类别从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 ::*常数,并且我使用了枚举类的全名。如果这变得太大了,没有什么可以阻止我对其他文件的别名。
- 在命名空间中使用全局命名空间中的函数
- 类与命名空间的全局实例
- 将好友从模板导出到全局命名空间
- Catalina C++:使用<cmath>标头产生错误:全局命名空间中没有名为 'signbit' 的成员
- 将以"_[a-z0-9]"开头和"using"的标识符导入全局命名空间是否定义良
- C++从 std::async 函数读取命名空间中的全局变量标志
- 为什么不允许在全局命名空间处阻止范围?
- 如何在命名空间中声明外部全局,然后定义它?
- 运算符<<依赖于参数的查找不在全局命名空间中查找
- 将C 枚举类成员拉入全局名称空间
- 我可以停止 GCC 将标准库名称包含在全局命名空间中吗?
- 在C 中将全局函数包括在命名空间中
- 为什么在全局范围以及命名空间std中定义了size_t
- 是否有一种方法可以避免标头文件中使用的constexpr函数输入全局范围,而无需额外的名称空间
- 无法找到在全局名称空间中定义的操作员
- 在全局空间中访问的私有静态对象
- 将面向方向的(局部空间)照相机投射到全局空间 x-y 平面
- 我在哪里放置类所需的常量,以保持全局空间自由
- 在全局空间中,在类的静态变量之前声明该类的对象是否定义良好
- 在全局空间中定义的类的构造函数代码何时运行?