这是一篇介绍bind和function用法的文章,起因是近来读陈硕的文章,提到用bind和function替代继承,于是就熟悉了下bind和function的用法,都是一些网上都有的知识,记录一下,期冀对他人也有用处。

注:本文暂时不探索bind和function的实现和开销。

1. bind 是什么

boost::bind 是std::bindlist 和 std::bind2nd的结合体。它提供一个任意的函数对象(仿函数)、函数、函数指针、成员函数指针。 它可以绑定任意的参数。bind 没有对函数对象有任何的要求。

2. bind 到函数/函数指针

void print(int array[], int size)
{
for (int i = ; i < size; i++) {
printf("%d\n", array[i]);
}
} int main(int argc, const char *argv[])
{
int array[]= {,,,,,,,,,};
int len = sizeof(array)/sizeof(array[]);
// 绑定普通函数 boost::bind(print, _1,_2)(array, len);
// 与function结合 boost::function<void(int [], int)> fn = boost::bind(print, _1,_2);
fn(array, len);
return ;
}

注意,_1 和_2 表示占位符。

3. bind到类成员函数

class Thread {p
public:
Thread (int id):thread_id(id)
{}
virtual void Run()
{
printf("this is threads %d\n", thread_id);
} private: int thread_id; }; class CallWrapper { public: typedef boost::function<void ()> CallBack; CallWrapper (); static void Run(CallBack fn) { printf("%s\t%d\n", __FUNCTION__, __LINE__); fn(); } }; int main() { Thread worker(); // 绑定类成员函数,worker相当于this指针 boost::bind(&Thread::Run, worker)(); // 作为参数,参数用function CallWrapper::Run(boost::bind(&Thread::Run, worker)); }

上面是一个比较简单的市立,下面给出一个比较适用的分行读取文件的例子

#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <stdio.h>
#include <string>
#include <map> class SimpleLineReader {
public:
SimpleLineReader (const string& filename)
{
fp_ = fopen(filename.c_str(), "r");
}
~SimpleLineReader (){
if (fp_) {
fclose(fp_);
}
}
typedef boost::function<bool (const std::string& line)> Callback;
bool ProcessLines(Callback fn)
{
if (!fp_)
{
return false;
}
char *line = NULL;
size_t len = ;
ssize_t read;
while ((read = getline(&line, &len, fp_)) != -) {
string str(line, read);
fn(line);
}
free(line);
return true;
}
private:
FILE* fp_;
}; class CityLoader {
public:
CityLoader (){}
int init(const std::string& filename)
{
SimpleLineReader reader(filename);
reader.ProcessLines(boost::bind(&CityLoader::ProcessLine, this, _1));
printf("readline\t%d\n", city_map_.size());
}
~CityLoader ()
{
}
private:
bool ProcessLine(const std::string& line)
{
static int cnt = ;
if (line.empty())
{
return true;
}
city_map_.insert(make_pair(++cnt, line));
return true;
}
std::map<int, std::string> city_map_;
};
void test_simple_line_reader()
{
CityLoader city_loader;
city_loader.init("data/city.txt");
}
int main()
{
test_simple_line_reader();
}

这就是全部了。个人认为比较方便。

boost::bind 和 boost::function 基本用法的更多相关文章

  1. boost::bind和boost::function使用示例

    C++11已支持bind和function,之前的不支持,但可以借助boost达到同样目的.看如下两段代码: 1) 创建HDFS目录 void hdfs::init() { if (0 == hdfs ...

  2. 用boost::bind构造boost::coroutine

    class TestCoro { ... typedef boost::coroutines::coroutione<void ()> Coro; void CoroFun(Coro::c ...

  3. [置顶] 编程模仿boost::function和boost::bind

    boost::function和boost::bind结合使用是非常强大的,他可以将成员函数和非成员函数绑定对一个对象上,实现了类似C#的委托机制.委托在许多时候可以替代C++里面的继承,实现对象解耦 ...

  4. 1,Boost -> Bind

    #include <boost/bind.hpp> #include <boost/shared_ptr.hpp> #include <iostream> usin ...

  5. boost::bind实践2——来自《Beyond the C++ Standard Library ( An Introduction to Boost )》

    直接代码: 代码段1: #include <iostream> #include <string> #include <boost/bind/bind.hpp> c ...

  6. boost::bind的使用方法

    bind - boost 头文件: boost/bind.hpp bind 是一组重载的函数模板.用来向一个函数(或函数对象)绑定某些参数. bind的返回值是一个函数对象. 它的源文件太长了. 看不 ...

  7. boost bind使用指南

    bind - boost 头文件: boost/bind.hpp bind 是一组重载的函数模板.用来向一个函数(或函数对象)绑定某些参数. bind的返回值是一个函数对象. 它的源文件太长了. 看不 ...

  8. boost asio 学习(二)了解boost::bind

    2.了解boost::bind使用boost::bind封装一个函数,考虑以下例子示例2a #include <iostream> #include <boost/bind.hpp& ...

  9. boost::bind四种应用场景的例子

        普通函数 int f( int a, int b ){return a + b;}boost::bind( f, _1, 9 )( 1 ) 成员函数 struct demo{int f( in ...

随机推荐

  1. .net通过获取客户端IP地址反查出用户的计算机名

    这个功能看似很少用到,但又非常实用,看似简单,但又在其中存在很多未知因素造成让人悲痛莫名的负能量... 这是公司内部最近在使用的功能,因为是DHCP,所以有时会根据计算机名做一些统计和权限的设置. 也 ...

  2. lightOJ 1172 Krypton Number System(矩阵+DP)

    题目链接:http://lightoj.com/volume_showproblem.php?problem=1172 题意:一个n进制(2<=n<=6)的数字,满足以下条件:(1)至少包 ...

  3. Python错误处理

    中文注释出错,把UTF-8标明放在文件头就行了 # coding: utf-8

  4. javac编译过程

    编译器把一种语言规范转化为另一种语言规范的这个过程需要哪些步骤:

  5. asp.net批量发布博客到各大博客平台

    新浪博客 http://upload.move.blog.sina.com.cn/blog_rebuild/blog/xmlrpc.php 网易博客 http://os.blog.163.com/ap ...

  6. Selenium Tutorial (1) - Starting with Selenium WebDriver

    Starting with Selenium WebDriver Selenium WebDriver - Introduction & Features How Selenium WebDr ...

  7. [cocos2d-x·解Bug]关于cocos2d-x游戏在android锁屏状态下播放Bgm的解决方法

    最近<宠物联萌>在三星App上发布遇到一个问题:如果用户在锁定屏幕时解锁解到一半时取消解锁,这时用cocos2d-x开发的游戏就会出现游戏Bgm会恢复播放,但手机屏幕仍然是锁屏状态的Bug ...

  8. $('div','li')

    要搞清楚$('div','li') 和 $('div , li') 和 $('div  li') 区别$('div','li')是$(子,父),是从父节点里找子,而不是找li外面的div $('div ...

  9. LeetCode: MergekSortedLists

    Title: Merge k sorted linked lists and return it as one sorted list. Analyze and describe its comple ...

  10. javaScript的函数(Function)对象的声明(@包括函数声明和函数表达式)

    写作缘由: 平时再用js写函数的时候,一般都是以惯例 function fn () {} 的方式来声明一个函数,在阅读一些优秀插件的时候又不免见到 var fn = function () {} 这种 ...