0

有没有办法做这样的事情(MS VS 2008)?

boost::bind mybinder = boost::bind(/*something is binded here*/);
mybinder(/*parameters here*/); // <--- first call
mybinder(/*another parameters here*/); // <--- one more call

我试过

int foo(int){return 0;}

boost::bind<int(*)(int)> a = boost::bind(f, _1);

但它不起作用。

4

2 回答 2

3
int foo(int){return 0;}
boost::function<int(int)> a = boost::bind(f, _1);
于 2011-09-16T11:47:16.327 回答
2

绑定返回未指定的类型,因此您不能直接创建该类型的变量。然而,有一个类型模板boost::function可以为任何函数或仿函数类型构造。所以:

boost::function<int(int)> a = boost::bind(f, _1);

应该做的伎俩。另外,如果您不绑定任何值,仅绑定占位符,则可以完全不绑定bind,因为function也可以从函数指针构造。所以:

boost::function<int(int)> a = &f;

只要是就应该f工作int f(int)。该类型使其适用于 C++11,std::function以便与 C++11 闭包一起使用(并且bind,也被接受):

std::function<int(int)> a = [](int i)->int { return f(i, 42); }

请注意,对于在 C++11 中直接调用它,新的使用auto更容易:

auto a = [](int i)->int { return f(i, 42); }

但如果你想传递它,std::function仍然会派上用场。

于 2011-09-16T11:47:53.547 回答