如何在C ++中将枚举导入到不同的命名空间中? [英] How do you import an enum into a different namespace in C++?

查看:254
本文介绍了如何在C ++中将枚举导入到不同的命名空间中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个命名空间中的枚举,我想使用它,如果它在一个不同的命名空间。直觉上,我想我可以使用使用或typedef来完成这一点,但两者都不工作。代码段以证明它,并在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;
}

这篇关于如何在C ++中将枚举导入到不同的命名空间中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆