Boost logo

Boost Users :

Subject: Re: [Boost-users] [lambda][optional] Accessing an optional variable through lambda
From: Nathan Crookston (nathan.crookston_at_[hidden])
Date: 2010-08-12 02:50:44


Hi Ryan,

On Wed, Aug 11, 2010 at 8:05 PM, Ryan McConnehey <mccorywork_at_[hidden]> wrote:
> I'm trying to create a stream operator for a list of DataPoint objects.  I
> can't get the correct boost::lambda syntax to access what the optional is
> containing.  Could someone tell me what I'm doing wrong?
>

The problem appears to be that boost::optional<double>::get is
overloaded -- there's a const and a non-const version. The most
straightforward solution appears to be a cast:

#include <boost/optional.hpp>
#include <boost/lambda/bind.hpp>
#include <boost/lambda/lambda.hpp>

#include <iostream>
#include <list>

struct DataPoint
{
 boost::optional<double> m_Time;
};

std::ostream & operator<<(std::ostream & stream,
                          std::list<DataPoint> const& points)
{
  namespace bll = boost::lambda;

  std::for_each(
     points.begin(),
     points.end(),
     stream << bll::bind(static_cast<double
const&(boost::optional<double>::*)()
const>(&boost::optional<double>::get),
         bll::bind(&DataPoint::m_Time, bll::_1)) << " ");

  return stream;
}

int main()
{
  DataPoint pt;
  pt.m_Time = boost::optional<double>(5.);
  std::list<DataPoint> points(5, pt);

  std::cout << points << std::endl;

  return 0;
}

However, the syntax is opaque. What you suggested in your comment
should work and would be nice, but I was also unable to parse the
error messages for it. To do what you'd like with Boost.Phoenix
(#include <boost/spirit/home/phoenix.hpp> to get all of it) you could
replace most of operator<< with the following:

namespace bp = boost::phoenix;
std::for_each(points.begin(), points.end(),
  stream << *bp::bind(&DataPoint::m_Time, bp::arg_names::_1) << " ");

Much cleaner, if that option's available to you.

Good luck,

Nate


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net