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 绑定


基础教程推荐
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 使用从字符串中提取的参数调用函数 2022-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 从 std::cin 读取密码 2021-01-01