Boost logo

Boost Users :

Subject: Re: [Boost-users] Bind to a member's class method.
From: Adam Romanek (romanek.adam_at_[hidden])
Date: 2014-03-21 08:59:57


On 03/21/2014 12:31 PM, Konrad Rybacki wrote:
> Unfortunately, with the code you have proposed I get the following error:
>
> ...
>
> And so on...

Sorry, I didn't test it, just assumed this was the source of the problem.

After some struggling I finally managed to fix the code, however the
solution isn't perfect.

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

#include <iostream>
#include <map>

class Test
{
public:
     typedef boost::optional<boost::variant<int, std::string>> Value;
     typedef Value::reference_const_type
(Value::*GetValueOrConstFn)(Value::reference_const_type) const;
     Value m_value;
};

int main(int argc, const char* argv[])
{
     Test t1, t2;

     std::string empty("empty");

     auto b1 = boost::lambda::bind(&Test::m_value, boost::lambda::_1);

     // static_cast is based on http://stackoverflow.com/a/2862235/1776942
     auto b2 =
boost::lambda::bind(static_cast<Test::GetValueOrConstFn>(&Test::Value::get_value_or),
boost::lambda::_1, empty);

     b1(t1) = "Test value";

     std::cout << b2(b1(t1)) << '\n'; // "Test value"
     std::cout << b2(b1(t2)) << '\n'; // Should be "empty"

     return 0;
}

The first problem was that boost::lambda::bind can't infer the return
type out of overloaded member function (see [1] for a related SO
question). The second problem was that b2 functor was passed an invalid
argument. The argument passed was of Test type, not Test::Value, as
expected by Test::Value::get_value_or().

Note that you could replace boost::lambda::bind with boost::bind to get
rid of this ugly static_cast:

auto b2 =
boost::bind<Test::Value::reference_const_type>(&Test::Value::get_value_or,
_1, empty);

This works too and looks much better.

P.S. I compiled it using clang on Ubuntu Linux so I had to change some
minor bits in the code.

WBR,
Adam Romanek


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