简体   繁体   English

C ++; 如何在名称空间中使用全局令牌

[英]C++; How to use a Global token within a namespace

I am extending an existing component which defines global TRUE and FALSE tokens. 我正在扩展定义全局TRUE和FALSE令牌的现有组件。 My extension is defining, within a new namespace 'new_namespace' an enum 'new_enum' which has values TRUE and FALSE. 我的扩展名是在新名称空间“ new_namespace”中定义一个枚举“ new_enum”,其值为TRUE和FALSE。 The compiler is failing to compile this because of a namespace collision. 由于名称空间冲突,编译器无法对此进行编译。

#define FALSE (0)
#define TRUE (1)

namespace new_namespace {
  class new_class {
  public :
  enum new_enum {
    TRUE = (0),
    FALSE = (1)
  };
  };
}

I would have hoped this would have been supported ... am I missing something. 我希望这会得到支持...我是否缺少某些东西。

Best Regards 最好的祝福

Macros are handled by the preprocessor, which (as the name implies) runs before the compiler proper. 宏由预处理器处理,顾名思义,预处理器在编译器适当运行之前运行。 What it does is replace the macro "call" with the text in the macro body. 它的作用是宏“ call” 替换为宏主体中的文本。 So what your enum looks like after the preprocessor step, and what the actual compiler sees, is: 因此,在预处理步骤之后,您的enum是什么样的,以及实际的编译器看到的是:

enum new_enum {
    (1) = (0),
    (0) = (1)
};

This is not legal C++, and the reason the compiler complains. 这不是合法的C ++,也是编译器抱怨的原因。

Joachim has identified your problem correctly so I won't repeat the answer. Joachim已正确识别您的问题,因此我不再重复。 But I want to comment on how to solve it. 但我想评论如何解决。 There is really no reason to have those tokens as defines, I would strongly advocate replacing them like this: 确实没有理由定义这些标记,我强烈建议这样替换它们:

const bool TRUE = true;
const bool FALSE = false;

It's just possible that this will result in type problems, although it's most likely that they will gracefully by implicitly cast. 这很可能会导致类型问题,尽管很有可能通过隐式强制转换来优雅地解决它们。 If you do see typing problems, try this instead: 如果确实看到键入问题,请尝试以下操作:

const int TRUE = 1;
const int FALSE = 0;

Either way these constants will obey the normal scoping rules and no longer conflict. 无论哪种方式,这些常量都将遵守常规的作用域规则,并且不再发生冲突。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM