Search code examples
c++boostboost-optional

Use boost::optional together with boost::adaptors::indirected


I am trying to compile the following code:

#include <iostream>
#include <iterator>
#include <vector>

#include <boost/assign/std/vector.hpp>
#include <boost/optional.hpp>
#include <boost/range/adaptor/indirected.hpp>
#include <boost/range/algorithm/copy.hpp>

int main( int argc, char ** argv )
{
  using namespace boost::assign;
  using boost::adaptors::indirected;

  std::vector<boost::optional<unsigned> > values;
  values += 1u,2u,3u;
  boost::copy( values | indirected, std::ostream_iterator<unsigned>( std::cout, " " ) );
  std::cout << std::endl;
}

However, I got some errors, e.g. that there is no type named element_type in boost::optional<unsigned>. The reference page page, however, says that the single precondition is the existence of the operator*() unary function. Is there a way to make it work?


Solution

  • This is definitely a bug in Boost, but whether that bug is in Boost.Optional or Boost.Iterator is up for debate (I would say the latter, personally).

    However, the fix is trivial -- before including any Boost headers, do this:

    #include <boost/optional/optional_fwd.hpp>
    #include <boost/pointee.hpp>
    
    namespace boost
    {
        template<typename P>
        struct pointee<optional<P> >
        {
            typedef typename optional<P>::value_type type;
        };
    }
    

    Then include other Boost headers as necessary.

    Please submit a ticket on the Boost Trac, or at the least post a bug report on the Boost Users mailing list.