【发布时间】:2011-12-19 02:21:35
【问题描述】:
这与上一个问题有关:Using boost::bind with boost::function: retrieve binded variable type。
我可以像这样绑定一个函数:
在.h中:
class MyClass
{
void foo(int a);
void bar();
void execute(char* param);
int _myint;
}
在.cpp中
MyClass::bar()
{
vector<boost::function<void(void)> myVector;
myVector.push_back(boost::bind(&MyClass::foo, this, MyClass::_myint);
}
MyClass::execute(char* param)
{
boost::function<void(void)> f = myVector[0];
_myint = atoi(param);
f();
}
但是我怎样才能绑定一个返回值呢?即:
在.h中:
class MyClass
{
double foo(int a);
void bar();
void execute(char* param);
int _myint;
double _mydouble;
}
在.cpp中
MyClass::bar()
{
vector<boost::function<void(void)> myVector;
//PROBLEM IS HERE: HOW DO I BIND "_mydouble"
myVector.push_back(boost::bind<double>(&MyClass::foo, this, MyClass::_myint);
}
MyClass::execute(char* param)
{
double returnval;
boost::function<void(void)> f = myVector[0];
_myint = atoi(param);
//THIS DOES NOT WORK: cannot convert 'void' to 'double'
// returnval = f();
//MAYBE THIS WOULD IF I COULD BIND...:
// returnval = _mydouble;
}
【问题讨论】:
-
你有一个
function<void(void)>——你认为double会出现在哪里?如果您想要一个返回double的空值function<>,请尝试function<double()>... -
看
bar函数的最后一行,输入参数是这样绑定的,函数类型被擦除变成function<void(void>>,但_myint仍然是链接的..我想要返回值也一样。关键是能够将所有 boost::functions 存储在同一个向量中;) -
但是你已经明确指定你想要
void作为返回值(function<void(void)>);要么你想要void,要么你想要double,你不能同时拥有。 -
我同意
returnval = f();不应该工作,但应该有一种方法来绑定返回值,就像有一种方法来绑定输入值...... -
不,Boost.Bind 绑定函数和参数。函数的执行和结果的返回值与调用常规函数完全相同。
标签: c++ boost boost-bind boost-function