是否可以检测在给定的代码点是否在命名空间中?特别是,如果文件被包含在全局命名空间中,我想包含一个警告。

最佳答案

如果头不包含在全局命名空间中,我可以给你一个提示,它会生成编译错误。如果我知道 C++ 结构肯定会产生编译器警告(除了#warning),那么它可以用来代替编译错误。

放入你的标题:

template <class A, class B>
struct AreSame { enum { VALUE = -1 }; };
template <class A>
struct AreSame<A,A> { enum { VALUE = 1 }; };

struct TestGlobalNamespace
{
   int test_namespace[AreSame<TestGlobalNamespace, ::TestGlobalNamespace>::VALUE];
};

当您的 header 包含在某个命名空间中时,您会收到错误消息。

就像在这个例子中:
namespace Some {

struct TestGlobalNamespace
{
   int test_namespace[AreSame<TestGlobalNamespace, ::TestGlobalNamespace>::VALUE];
};

}

你会得到:
prog.cpp:17: error: size of array ‘test_namespace’ is negative

[更新]

然而,更可能是这种错误:
prog.cpp:17: error: ‘::TestGlobalNamespace’ has not been declared
prog.cpp:17: error: template argument 2 is invalid

无论如何 - 除了全局之外,没有人敢将您的 header 包含在命名空间中。

关于c++ - 在 C++ 中检测命名空间,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12410192/

10-11 22:46
查看更多