如何将枚举导入 C++ 中的不同命名空间?
我在命名空间中有一个枚举,我想像在不同的命名空间中一样使用它.直觉上,我认为我可以使用使用"或类型定义"来完成此操作,但实际上都不起作用.证明它的代码片段,在 GCC 和 Sun CC 上测试:
I have an enum in a namespace and I'd like to use it as if it were in a different namespace. Intuitively, I figured I could use 'using' or 'typedef' to accomplish this, but neither actually work. Code snippet to prove it, tested on GCC and Sun CC:
namespace foo
{
enum bar {
A
};
}
namespace buzz
{
// Which of these two methods I use doesn't matter,
// the results are the same.
using foo::bar;
//typedef foo::bar bar;
}
int main()
{
foo::bar f; // works
foo::bar g = foo::A; // works
buzz::bar x; // works
//buzz::bar y = buzz::A; // doesn't work
buzz::bar z = foo::A;
}
问题是枚举本身是导入的,但没有任何元素.不幸的是,在不破坏大量其他现有代码的情况下,我无法将原始枚举更改为包含在额外的虚拟命名空间或类中.我能想到的最佳解决方案是手动重现枚举:
The problem is that the enum itself is imported but none of its elements. Unfortunately, I can't change the original enum to be encased in an extra dummy namespace or class without breaking lots of other existing code. The best solution I can think of is to manually reproduce the enum:
namespace buzz
{
enum bar
{
A = foo::A
};
}
但它违反了DRY 原则.有没有更好的办法?
But it violates the DRY principle. Is there a better way?
推荐答案
将现有命名空间包装在嵌套命名空间中,然后在原始命名空间中使用"该命名空间.
Wrap the existing namespace in a nested namespace which you then "use" in the original namespace.
namespace foo
{
namespace bar_wrapper {
enum bar {
A
};
}
using namespace bar_wrapper;
}
namespace buzz
{
using namespace foo::bar_wrapper;
}
相关文章