At work I\'ve been using linux and the GCC compiler for C++11 and C++14. In some of the code at work, I\'ve used a union to store both a reference and a pointer, as so: (Sim
It is illegal for a union to contain a reference member. This is presumably because references are not objects and it's unspecified whether or not they occupy storage---so it makes little sense for a reference to share its storage with other variables.
A union can have member functions (including constructors and destructors), but not virtual (10.3) functions. A union shall not have base classes. A union shall not be used as a base class. If a union contains a non- static data member of reference type the program is ill-formed.
([class.union]/2)
In addition to @Brian:
You can make it compile by using e.g. std::reference_wrapper
instead of a plain reference:
#include <functional>
struct MyStruct
{
//Stuff
union { std::reference_wrapper<double> x; double* x_ptr; };
MyStruct(double& value) : x(value) {}
//More stuff
};
int main()
{
double value = 123;
MyStruct myStruct(value);
}
live example