ham*_*mcn 74 c++ boost boost-bind boost-function
以下代码导致cl.exe崩溃(MS VS2005).
我试图使用boost bind来创建一个调用myclass方法的函数:
#include "stdafx.h"
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <functional>
class myclass {
public:
void fun1() { printf("fun1()\n"); }
void fun2(int i) { printf("fun2(%d)\n", i); }
void testit() {
boost::function<void ()> f1( boost::bind( &myclass::fun1, this ) );
boost::function<void (int)> f2( boost::bind( &myclass::fun2, this ) ); //fails
f1();
f2(111);
}
};
int main(int argc, char* argv[]) {
myclass mc;
mc.testit();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
Geo*_*che 102
请改用以下内容:
boost::function<void (int)> f2( boost::bind( &myclass::fun2, this, _1 ) );
Run Code Online (Sandbox Code Playgroud)
这将使用占位符将传递给函数对象的第一个参数转发给函数 - 您必须告诉Boost.Bind如何处理参数.使用您的表达式,它会尝试将其解释为不带参数的成员函数.
有关常见的使用模式,请参见此处或此处.
请注意,VC8s cl.exe会在Boost.Bind上经常崩溃- 如果有疑问,请使用带有gcc的测试用例,你可能会得到很好的提示,比如模板参数Bind -internals如果你通读输出就会被实例化.
归档时间: |
|
查看次数: |
105499 次 |
最近记录: |