I tried to learn more about associations and their usefulness when I was surprised that the following code is absolutely correct and works exactly as expected:
template <class T> union Foo { T a; float b; Foo(const T& value) : a(value) { } Foo(float f) : b(f) { } void bar() { } ~Foo() { } }; int main(int argc, char* argv[]) { Foo<int> foo1(12.0f); Foo<int> foo2((int) 12); foo1.bar(); foo2.bar(); int s = sizeof(foo1);
Until now, I had no idea that it is legal to declare unions with templates, constructors, destructors, and even member functions. If relevant, I am using Visual Studio 2012.
When I searched the Internet to find more about using unions in this way, I did not find anything. Is this a new C ++ feature or something special for MSVC? If not, I would like to know more about unions, in particular, examples from them were used as classes (see above). If someone could point me to a more detailed explanation of the unions and their use as data structures, it would be very grateful.
source share