Andrej Mitrović
Andrej Mitrović

Reputation: 3342

Is there any way to gain access to protected declarations inside unions?

I'm asking this in the context of generating wrapper bindings for C++ libraries. Sample code:

union Union
{
protected:
    struct ProtClass
    {
    };
};

Wrapper bindings are written with extern "C" functions, which require types to be accessible (IOW a nested type declaration must be public). A simple workaround for accessing protected declarations in classes is to inherit from the class and use the public redeclaration feature of C++ which enables using the declarations in extern "C" functions. For example:

class Class
{
protected:
    struct NestClass
    {
    };
};

class PubDeclClass : Class  // autogenerated
{
public:
    Class::NestClass;  // redeclare nested class as public (can also use 'using' here)
};

// autogenerated (normally generated only if NestClass isn't a POD type)
void* getNewNestClass() { return new PubDeclClass::NestClass; }

Simple enough, but this trick can't be used with unions since they can't be inherited from. Do you know of any trick I could use to be able to access a union's nested protected declarations from an extern "C" function?

The purpose of allowing this is to create a 1-to-1 mirror of a C++ library in the target language, meaning that the target language would have the same access specifiers as in the library. The "C" functions are the glue between the C++ code and the target language code (SWIG uses this method as well, although it doesn't always wrap nested declarations).

Personally, I'd love to have some sort of g++ extension that I could use to redeclare a non-public symbol as public with some special syntax, for the sole purpose of writing library wrappers. This would simplify my codegenerator immensely.

Upvotes: 3

Views: 193

Answers (1)

Kirill Kobelev
Kirill Kobelev

Reputation: 10557

Why can't you use a simple wrapper:

struct UnionWrapper
{
    union
    {
    protected:
        struct ProtClass { };
    };
};

class Z12 : public UnionWrapper
{
};

This is just a work around the phohibition.

Upvotes: 0

Related Questions