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

▼魔方 西西 提交于 2019-12-08 17:31:16

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/6123327/use-boostoptional-together-with-boostadaptorsindirected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!