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

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

问题描述

我有一个命名空间中的枚举,我想使用它,就像它在一个不同的命名空间。直观地,我想我可以使用'use'或'typedef'来完成这个,但实际上并不奏效。代码片段来证明它,在GCC和Sun CC上测试:

 命名空间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屋!

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