C++ 使用boost::函数和boost::绑定到成员变量
我正在尝试创建一个boost::函数,该函数允许设置对象的成员变量。我已经创建了一个我能想到的最简单的例子来理解我正在尝试(和失败)做什么。我觉得我已经掌握了boost::bind,但我对boost还不熟悉,我相信我使用boost::function的方法不正确C++ 使用boost::函数和boost::绑定到成员变量,c++,boost,function-pointers,boost-bind,boost-function,C++,Boost,Function Pointers,Boost Bind,Boost Function,我正在尝试创建一个boost::函数,该函数允许设置对象的成员变量。我已经创建了一个我能想到的最简单的例子来理解我正在尝试(和失败)做什么。我觉得我已经掌握了boost::bind,但我对boost还不熟悉,我相信我使用boost::function的方法不正确 #include <iostream> #include <Boost/bind.hpp> #include <boost/function.hpp> class Foo { public:
#include <iostream>
#include <Boost/bind.hpp>
#include <boost/function.hpp>
class Foo
{
public:
Foo() : value(0) {}
boost::function<void (int&)> getFcn()
{
return boost::function<void (int&)>( boost::bind<void>( Foo::value, this, _1 ) );
}
int getValue() const { return value; }
private:
int value;
};
int main(int argc, const char * argv[])
{
Foo foo;
std::cout << "Value before: " << foo.getValue();
boost::function<void (int&)> setter = foo.getFcn();
setter(10); // ERROR: No matching function for call to object of type 'boost::function<void (int &)>'
// and in bind.hpp: Called object type 'int' is not a function or function pointer
std::cout << "Value after: " << foo.getValue();
return 0;
}
#包括
#包括
#包括
福班
{
公众:
Foo():值(0){}
boost::函数getFcn()
{
返回boost::function(boost::bind(Foo::value,this,_1));
}
int getValue()常量{返回值;}
私人:
int值;
};
int main(int argc,const char*argv[]
{
富富,;
std::coutThisboost::bind(Foo::value,This,_1)
在您的代码中基本上使用了Foo::value
作为成员函数。这是错误的。Foo::value
不是函数
让我们一步一步地构建:
class Foo
{
...
boost::function< void (Foo*, int) > getFcn ()
{
return boost::function< void (Foo*, int) >( &Foo::setValue );
}
void setValue (int v)
{
value = v;
}
...
}
int main ()
{
...
boost::function< void (Foo*, int) > setter = foo.getFcn();
setter( &foo, 10);
...
}
(未测试代码)我试图避免在类中为每个我想这样做的变量都使用setter方法。我正在寻找一种直接修改变量的方法。boost::function可以不这样使用吗?@NicFoster,我相信不行。boost。function是行为类似于函数的事物的包装器。您试图将其包装在int
上够了,我假设既然可以使用bind绑定到成员变量,那么就可以使用函数
来设置这些成员变量。
class Foo
{
...
boost::function< void (int) > getFcn ()
{
return boost::bind(&Foo::setValue, this, _1);
}
void setValue (int v)
{
value = v;
}
...
}
int main ()
{
...
boost::function< void (int) > setter = foo.getFcn();
setter( 10);
...
}