Is any mainstream compiler likely to support C++0x unrestricted unions in the near future?
I keep looking, but it seems like there's zero interest from compiler developers in supporting these.
To me, it seems odd - basically, current C++ has restrictions on unions that were always an irritation and never appropriate. You'd think that basically removing a few error checks would be a relatively simple way to tick an extra c++0x support box, but AFAICT no compiler developers have done so yet.
Why I'm interested is because it provides a simple solution to a recurring problem in data structure coding - how to reserve memory for an instance of some unknown (template parameter) type, preferably with as much type safety as possible in the circumstances, but without invoking any constructor that happens to be defined on that type. The really important point is that alignment rules must be followed.
An unrestricted union is perfect for this - it gives you a type which has no construc开发者_StackOverflowtors or destructors, but which has the right size and alignment to allow any member. There are of course ways to explicitly construct and destruct when needed, and when you need typesafe access, you just use the appropriate union member to access it. Support for "proper" unions can be useful too, but you get huge benefits even for a single-member union such as...
union Memory_For_Item_t
{
Item_t m_Item;
};
Even with the standardized alignment handling features in C++0x, this approach wins for convenience and safety when e.g. you want space for x items in a node, not all of which will be in use (or constructed) at any time. Without C++0x, we are still in the dark ages WRT alignment issues - every compiler does it its own non-standard way.
The only problem with unrestricted unions - there's no support for them that I can find.
Near future? I wouldn't count on it. As http://wiki.apache.org/stdcxx/C%2B%2B0xCompilerSupport lays out well, none of the current compilers support it even though many over C++0x features are being implemented.
However as N2544 explains:
The current work-around to the union limitations is to create a fake union using template programming or casts.
So, the situation you are describing probably already has a solution, although a bit messy.
GCC now lists it as supported in version 4.6. It seems to have been introduced on july 14th, with this patch. The future is now.
Yeah - I have a template approach now, but it relies on preprocessor conditionals to identify compilers and other nastiness, mainly to get the alignment handling right. IOW it's brittle and generally nasty
Why don't you just use boost::variant? if you're not going to use boost and you're already using C++0x then use type traits such as std::alignment_of/std::aligned_storage
those are standardized and cross-platform and if your compiler supports them now you can use variadic templates. Use template meta-programming to compute the largest type in the type list etc.
精彩评论