bind作为左值对象

boost::bind as l-value object

本文关键字:对象 bind      更新时间:2023-10-16

是否有办法这样做(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);

int foo(int){return 0;}
boost::function<int(int)> a = boost::bind(f, _1);

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

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

就可以了。另外,如果您没有绑定任何值,只有占位符,您可以完全不使用bind,因为function也可以从函数指针构造。所以:

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

就可以工作。该类型作为std::function出现在c++ 11中,用于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还是很有用的