I have an optional POD struct that will be contained inside a union.
boost::optional<>
holds its type by value, so I thought this could work:
union helper
{
int foo;
struct
{
char basic_info;
struct details {
//...
};
boost::optional<details> extended_info;
} bar;
// ...
};
helper x = make_bar();
if( x.bar.extended_info )
{
// use x.bar.extended_info->elements
}
but VS2008 complained that my bar
struct now had a copy constructor due to the boost::optional<details>
element.
As a replacement, I've added a boolean flag to indicate whether the optional parameter is valid, but it's clunky:
union helper
{
int foo;
struct
{
char basic;
struct details {
bool valid;
//...
} extended;
} bar;
// ...
};
I considered implementing details::operator bool()
to return the details::valid
variable, but that's obscure and a disservice to humanity.
boost::optional<>
clearly documents the syntax and intent and doesn't require detective work.
Finally, the helper
union needs to be POD, so I can't do any dynamic allocation - otherwise I would use a pointer.
Any suggestions for something syntactically similar to boost::optional<>
that's usable in a union?
helper
union need to account for the size of yourbar
struct? – Forthcoming