问题描述
以下代码导致 cl.exe 崩溃(MS VS2005).
我正在尝试使用 boost bind 创建一个函数来调用 myclass 的方法:
The following code causes cl.exe to crash (MS VS2005).
I am trying to use boost bind to create a function to a calls a method of myclass:
#include "stdafx.h"
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <functional>
class myclass {
public:
void fun1() { printf("fun1()
"); }
void fun2(int i) { printf("fun2(%d)
", 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 ) );
这使用占位符将传递给函数对象的第一个参数转发给函数 - 您必须告诉 Boost.Bind 如何处理这些参数.使用您的表达式,它会尝试将其解释为不带参数的成员函数.
见例如此处 或 此处了解常见的使用模式.
This forwards the first parameter passed to the function object to the function using place-holders - you have to tell Boost.Bind how to handle the parameters. With your expression it would try to interpret it as a member function taking no arguments.
See e.g. here or here for common usage patterns.
请注意,VC8s cl.exe 经常因 Boost.Bind 误用而崩溃 - 如果有疑问,请使用带有 gcc 的测试用例,您可能会得到很好的提示,例如模板参数 Bind<如果您通读输出,/em>-internals 会被实例化.
Note that VC8s cl.exe regularly crashes on Boost.Bind misuses - if in doubt use a test-case with gcc and you will probably get good hints like the template parameters Bind-internals were instantiated with if you read through the output.
这篇关于如何使用带有成员函数的 boost 绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!