Boost :: optional <> in union?

I have an optional POD structure that will be contained within the union.
boost::optional<>keeps its type by value, so I thought this might 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 structure barnow had a copy constructor due to the element boost::optional<details>.

As a replacement, I added the boolean flag to indicate whether the optional parameter is valid, but it is awkward:

union helper
{
    int foo;
    struct 
    {
        char basic;
        struct details {
            bool valid;
            //...
        } extended;
    } bar;
    //  ...
};

I considered the possibility of implementation details::operator bool()to return a variable details::valid, but it is unclear and harmful to humanity.
boost::optional<>clearly documents syntax and intention and does not require detective work.

, helper POD, - .

- boost::optional<>, ?

+5
2

, - union boost::variant<>.

, , POD boost::optional<> :

template <typename T>
class Optional
{
    T value;
    bool valid;

public:

    // for the if(var) test
    operator bool() const  {  return valid;  }

    //  for assigning a value
    Optional<T> &operator=(T rhs)   
    {  
        value = rhs;  
        valid = true;  
        return *this;  
    }

    //  for assigning "empty"
    Optional<T> &operator=(void *)  
    {  
        valid = false;  
        return *this;  
    }

    // non-const accessors
    T &operator*()   {  return  value;  }
    T *operator->()  {  return &value;  }

    // const accessors
    const T &operator*()  const  {  return  value;  }
    const T *operator->() const  {  return &value;  }
};

- , const Optional<>.

, Optional<T> , ( ).
boost::optional<T>, Optional<T> T Optional<T>.
value null , operator Optional<T>(). .

Optional<details> additional_info;
Optional<details> more_info(additional_info);

// if there no additional info
additional_info = 0;

// if there is extended info
details x;
//  ...populate x...
additional_info = x;

if( extended_info )
{
    extended_info->member;
    // - or -
    details &info = *extended_info;
}

- . , .

0

-POD- . boost:: variant - ++ . , C.

+13

All Articles