Binding to Member Variables

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 something wrong? G ++ 4.4.0 compiler

+3
source share
3 answers

UncleBens solution is ok, but I thought I would add that if you use Boost.Lambda, the problem goes away:

#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, if you use boost::mem_fn:

#include <boost/mem_fn.hpp>

struct A {
    int data;
};

int main() {

    boost::mem_fn(&A::data)(a) = 1;
}
+2
source

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

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

I'm not sure what you want to do, but does Boost.Bind really overload the assignment operator? If you want to assign the value 1 a.data using the returned object of the function, I think you need to do something like this (also note that “a” needs to be linked 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 an assignment operator, I think using Boost.Lambda or Boost.Phoenix would be a better choice.

+1
source

Source: https://habr.com/ru/post/1732775/


All Articles