以下代码导致 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;
}
我究竟做错了什么?
请改用以下内容:
boost::function<void (int)> f2( boost::bind( &myclass::fun2, this, _1 ) );
这使用占位符将传递给函数对象的第一个参数转发给函数 - 你必须告诉升压绑定如何处理参数。对于您的表达式,它会尝试将其解释为不带参数的成员函数。
参见例如here or here对于常见的使用模式。
请注意,VC8s cl.exe 经常崩溃升压绑定误用 - 如果有疑问,请使用 gcc 的测试用例,您可能会得到很好的提示,例如模板参数Bind- 如果您阅读输出,则内部会被实例化。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)