Search code examples
c++namespacesunions

Access to class inside Union


I have the declaration of class Ainside a third party library, so I can't modify it. I need to use the declaration of class B to pass it to a method, is there a way to do it without modifying class A?

When I try this:

#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;
}

I get the error:

error: B is not a member of A

Live Example!

My assumption is that it happens because B is in a unnamed namespace.

PS: If I could modify the declaration of the union from:

union {...

to:

union T {...

This will be done simple by:

A::T::B test;

Solution

  • You can get the type of the union using decltype, then you can access B:

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

    coliru example