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:
下面的代码导致cl。紧急事故(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;
}
What am I doing wrong?
我做错了什么?
1 个解决方案
#1
91
Use the following instead:
使用以下:
boost::function<void (int)> f2( boost::bind( &myclass::fun2, this, _1 ) );
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.
这将把传递给函数对象的第一个参数传递给函数—您必须告诉Boost。绑定如何处理参数。使用您的表达式,它将尝试将它解释为一个成员函数,不带参数。在这里或这里查看常见的使用模式。
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.
注意,VC8s cl。exe经常在Boost中崩溃。绑定误用——如果对使用gcc使用一个测试用例有疑问的话,您可能会得到一些很好的提示,比如如果您通读输出,会发现模板参数Bind-internals被实例化了。
#1
91
Use the following instead:
使用以下:
boost::function<void (int)> f2( boost::bind( &myclass::fun2, this, _1 ) );
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.
这将把传递给函数对象的第一个参数传递给函数—您必须告诉Boost。绑定如何处理参数。使用您的表达式,它将尝试将它解释为一个成员函数,不带参数。在这里或这里查看常见的使用模式。
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.
注意,VC8s cl。exe经常在Boost中崩溃。绑定误用——如果对使用gcc使用一个测试用例有疑问的话,您可能会得到一些很好的提示,比如如果您通读输出,会发现模板参数Bind-internals被实例化了。