How to use boost bind with a member function(如何使用带有成员函数的 boost 绑定)
问题描述
以下代码导致 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 绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用带有成员函数的 boost 绑定
基础教程推荐
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- CString 到 char* 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 初始化列表*参数*评估顺序 2021-01-01
