Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid union member

Is there a way in Visual Studio to handle non-trivial unions. The following code is running fine using g++ -std=c++11 but VS complains:

invalid union member -- class "Foo" has a disallowed member function

The code is as follows:

struct Foo {
    int value;
    Foo(int inV = 0) : value(inV) {}
};

union CustomUnion {
    CustomUnion(Foo inF) : foo(inF) {}
    CustomUnion(int inB) : bar(inB) {}
    int bar;
    Foo foo;
};

int main() {
    CustomUnion u(3);
    return 0;
}

Is there a way in Visual Studio to support this kind of unions (compilation option for instance)? Or should I change my code, and if so by what?

like image 652
bagage Avatar asked Feb 23 '14 13:02

bagage


People also ask

How is a union declared?

Syntax for declaring a union is same as that of declaring a structure except the keyword struct. Note : Size of the union is the the size of its largest field because sufficient number of bytes must be reserved to store the largest sized field. To access the fields of a union, use dot(.)

Can a union have a constructor?

A union can have member functions (including constructors and destructors), but not virtual functions. A union cannot have base classes and cannot be used as a base class. A union cannot have non-static data members of reference types.

What can I use instead of union in C++?

In C++17 and later, the std::variant class is a type-safe alternative for a union. A union is a user-defined type in which all members share the same memory location. This definition means that at any given time, a union can contain no more than one object from its list of members.


3 Answers

I agree with @Shafik Yaghmour but there is an easy workaround.
Just put your foo member into an unnamed struct like so:

union CustomUnion {
    struct{
        Foo foo;
    };
    int bar;
};
like image 77
Quest Avatar answered Oct 06 '22 22:10

Quest


Visual Studio does not support unrestricted unions which is a C++11 feature that allows unions to contain non-POD types, in your case Foo has a non-trivial constructor since you have defined one.

I don't see any reference that says when Visual Studio will support this so it does not seem like you will get this to work as is in Visual Studio. Although there seems to be many who do want this feature supported.

The only way I can see to get to work would be to remove your user defined constructor from Foo. That would mean manually initializing foo in the CustomUinon constructor.

A good reference article would be: C++11 Standard Explained: 1. Unrestricted Union .

like image 30
Shafik Yaghmour Avatar answered Oct 06 '22 23:10

Shafik Yaghmour


As described in msdn, union just accesses members: 1) class type without any constructors or destructors, 2) static member, 3) class type without user defined assignment operation(override =).

like image 1
user3343412 Avatar answered Oct 06 '22 22:10

user3343412