是否有可能检测您是否在给定的代码点处在命名空间中?特别是,如果文件被包含在全局命名空间中,我想包含一个警告。
最佳答案
如果 header 不包含在全局命名空间中,我可以给你一个生成编译错误的提示。如果我知道 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 包含到全局以外的 namespace 中。
关于c++ - 在 C++ 中检测命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12410192/