访问Union内部的类

时间:2017-02-23 16:11:26

标签: c++ namespaces unions

我在第三方库中有类A的声明,所以我无法修改它。 我需要使用类B的声明将它传递给方法,有没有办法在不修改类A的情况下执行它?

当我尝试这个时:

#include <iostream>
using namespace std;
class A
{
    public:
    union {
        class B
        {
            public:
            int x;
        };
    }un;
};

void foo(A::B & test)
{
}

int main() {
    A::B test;
    test.x=10;
    cout << test.x << endl;
    return 0;
}

我收到错误:

  

错误:B不是A

的成员

Live Example!

我的假设是它发生是因为B在一个未命名的命名空间中。

PS:如果我可以修改union的声明 从:

union {...

为:

union T {...

这将通过以下方式完成:

A::T::B test;

1 个答案:

答案 0 :(得分:1)

您可以使用decltype获取联盟的类型,然后您可以访问B

decltype(std::declval<A&>().un)::B test;

coliru example

相关问题