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

fredoverflow
  • 256,549
  • 94
  • 388
  • 662
  • Just realized something following your example link above: you are trying to follow a Boost.Lambda bind expression example using Boost.Bind. Try to include and and use boost::lambda::bind + boost::lambda::_1 instead. Also, use boost::lambda::var to hold a by reference. – rjnilsson Feb 15 '10 at 08:15

3 Answers3

3

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
  • 40,819
  • 6
  • 57
  • 90
2

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
  • 12,749
  • 1
  • 27
  • 35
1

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.

rjnilsson
  • 2,343
  • 15
  • 20