Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 863
Mathias Soeken Avatar asked May 25 '11 10:05

Mathias Soeken


2 Answers

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.

like image 127
ildjarn Avatar answered Oct 21 '22 11:10

ildjarn


Look at the private optional.hpp defined in boost iostreams library here. You will see that it defines a typedef T element_type;

However the actual optional.hpp that you are using defined here does not define it. So that is why the compiler is complaining. I don't know why it was overlooked.

Try using the private optional.hpp from iostreams library to solve this issue. I hope this helps.

like image 40
O.C. Avatar answered Oct 21 '22 13:10

O.C.