如何将枚举导入到不同的命名空间中? [英] How do you import an enum into a different namespace in C++?
问题描述
命名空间foo
{
enum bar {
A
};
}
命名空间buzz
{
//我使用的这两种方法中的哪一种并不重要,
//结果是相同的。
使用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; //不工作
buzz :: bar z = foo :: A;
}
问题是枚举本身是导入的,但没有其元素。不幸的是,我不能将原来的枚举更改为包含在一个额外的虚拟命名空间或类中,而不会破坏大量其他现有的代码。我可以想到的最好的解决办法是手动重现枚举:
命名空间buzz
{
枚举bar
{
A = foo :: A
};
}
但它违反了 DRY原则。有没有更好的方法?
将现有命名空间包含在一个嵌套命名空间中,然后在原始命名空间中使用。
命名空间foo
{
命名空间bar_wrapper {
枚举栏{
A
};
}
使用命名空间bar_wrapper;
}
命名空间buzz
{
使用命名空间foo :: bar_wrapper;
}
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
};
}
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;
}
这篇关于如何将枚举导入到不同的命名空间中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!