以下来自Boost Bind的示例 对我不起作用:
#include <boost/bind.hpp>
struct A
{
int data;
};
int main()
{
A a;
boost::bind(&A::data, _1)(a) = 1;
}
错误:分配只读位置 'boost::bind [with A1 = boost::arg<1>, M = int, T = A](&A:: data, (::_1, boost::arg<1>())).boost::_bi::bind_t::operator() [其中 A1 = A, R = const int&,F = boost::_mfi::dm,L = boost::_bi::list1; >](((A&)(& a)))'
我做错了什么吗?编译器是g++ 4.4.0
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
发布评论
评论(3)
该绑定表达式的结果类型是
int
(或者更确切地说const int&
)。我认为你可以覆盖返回类型 :The result type of that bind expression is
int
(or ratherconst int&
). I think you can override the return type:UncleBens 的解决方案很好,但我想我应该补充一点,如果您使用 Boost.Lambda,问题就会消失:
如果您使用 boost::mem_fn,问题就会消失:
UncleBens' solution is fine but I thought I'd add that if you use Boost.Lambda the problem disappears:
And so it does if you use
boost::mem_fn
:我不确定你想做什么,但是 Boost.Bind 真的会重载赋值运算符吗?如果您想使用返回的函数对象将值 1 分配给 a.data 我认为您需要执行类似的操作(另请注意“a”需要通过引用绑定):
如果您需要使用赋值我认为使用 Boost.Lambda 或 Boost.Phoenix 会是更好的选择。
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):
If you need to use the assignment operator I think that using Boost.Lambda or Boost.Phoenix would be a better choice.