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?
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(.)
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.
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.
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;
};
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 .
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 =).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With