views:

246

answers:

3

The following example from boost bind does not work for me:

#include <boost/bind.hpp>

struct A
{
    int data;
};

int main()
{
    A a;
    boost::bind(&A::data, _1)(a) = 1;
}

error: assignment of read-only location 'boost::bind [with A1 = boost::arg<1>, M = int, T = A](&A::data, (<unnamed>::_1, boost::arg<1>())).boost::_bi::bind_t<R, F, L>::operator() [with A1 = A, R = const int&, F = boost::_mfi::dm<int, A>, L = boost::_bi::list1<boost::arg<1> >](((A&)(& a)))'

Am I doing anything wrong? The compiler is g++ 4.4.0

+1  A: 

The result type of that bind expression is int (or rather const int&). I think you can override the return type:

boost::bind<int&>(&A::data, _1)(a) = 1;
UncleBens
A: 

UncleBens' solution is fine but I thought I'd add that if you use Boost.Lambda the problem disappears:

#include <boost/lambda/bind.hpp>

struct A {
    int data;
};

int main() {

    namespace bll = boost::lambda;

    A a;
    bll::bind(&A::data, bll::_1)(a) = 1;
}

And so it does if you use boost::mem_fn:

#include <boost/mem_fn.hpp>

struct A {
    int data;
};

int main() {

    boost::mem_fn(&A::data)(a) = 1;
}
Manuel
A: 

I'm not sure what you want to do, but does Boost.Bind really overload the assignment operator? If you'd like to assign the value 1 to a.data using the returned function object I think you need to do something like this (also note that "a" needs to be bound by reference):

#include <boost/bind.hpp>
#include <boost/ref.hpp>
#include <cassert>

void foo()
{
    A a;

    boost::bind(&A::data, _1)(boost::ref(a), 1);

    assert(a.data == 1);
}

If you need to use the assignment operator I think that using Boost.Lambda or Boost.Phoenix would be a better choice.

Cwan