简体   繁体   English

C ++-通过宏定义的名称空间-如何在标头中使用它

[英]C++ - namespace via macro definition - how to use it in header

I have some code, that has namespace configurable by user as this: 我有一些代码,其中的名称空间可由用户配置,如下所示:

#pragma once

#ifdef GRAPHICS_NAMESPACE
namespace GRAPHICS_NAMESPACE {
#endif

class Foo {
}

#ifdef GRAPHICS_NAMESPACE
}
#endif

And in cpp file, there is 在cpp文件中

#ifdef GRAPHICS_NAMESPACE
using namespace GRAPHICS_NAMESPACE;
#endif

Now I have a problem. 现在我有一个问题。 I have defined -DGRAPHICS_NAMESPACE=Graphics and I have a header with: 我定义了-DGRAPHICS_NAMESPACE=Graphics并且具有以下标题:

#pragma once

#include "Foo.h"

class Bar {
   Foo foo;
}

But Foo foo gives me error, since Foo is in namespace now named Graphics . 但是Foo foo给我错误,因为Foo在现在命名为Graphics命名空间中。 I can solve this with adding 我可以通过添加解决

#ifdef GRAPHICS_NAMESPACE
using namespace GRAPHICS_NAMESPACE;
#endif

to my header, but that is not very safe since it will be using namespace everywhere where I include my header. 到我的标头,但这不是很安全,因为它将在我包含标头的所有地方使用命名空间。 Is there any other solution? 还有其他解决方案吗?

I would do it like this: 我会这样做:

#ifdef GRAPHICS_NAMESPACE 
#define GRAPHICS GRAPHICS_NAMESPACE 
#else
#define GRAPHICS 
#endif

...

GRAPHICS::Foo 

Although I would say this is not the optimal way to arrange things, I've seen worse and the solution to your problem is rather straightforward: 尽管我说这不是安排事物的最佳方法,但我看到了更糟糕的情况,解决问题的方法也很简单:

class Bar {

#ifdef GRAPHICS_NAMESPACE
GRAPHICS_NAMESPACE::
#endif
   Foo foo;
}

If you insist on sticking with this design, you can clean this up, somewhat, by defining a 2nd macro: 如果您坚持使用此设计,则可以通过定义第二个宏来对其进行某种程度的清理:

#ifdef GRAPHICS_NAMESPACE
#define GRAPHICS_CLASS(x)  GRAPHICS_NAMESPACE:: x
#else
#define GRAPHICS_CLASS(x)  x
#endif

And then declare things along the lines of: 然后按照以下方式声明:

class Bar {
   GRAPHICS_CLASS(Foo) foo;
}

Finally, if you insist on relying on the preprocessor for this kind of critical functionality, you may want to consider spending a little bit more time reading what your C++ book says on this topic. 最后,如果您坚持依赖预处理器来实现这种关键功能,则可能需要考虑花费更多时间阅读C ++书中关于该主题的内容。 These are fairly basic, straightforward uses of the C++ preprocessor, which I expect should be fully explained in any introduction on what a C++ preprocessor is, and how it works. 这些是C ++预处理程序的相当基本,直接的用法,我希望在任何有关C ++预处理程序及其工作原理的介绍中都应充分解释这些用法。

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

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