boost中function的简单应用(将function作为参数进行传递)

今天开发代码的时候发现前人的代码很多的重复,看的极累,因此考虑优化合并,结果发现需要动用到函数参数方能使得逻辑上看起来简单清晰。想到了boost的应用,可以比较简单的实现函数参数的功能。以下为简单的实现代码:

// testfunction_param.cpp : Defines the entry point for the console application.
// 一个简单的函数参数的应用,即将类函数作为一个入参,由别的函数通过此入参调用此函数。
// boost方法比较简单的解决了这个问题。

#include "stdafx.h"
#include <iostream>
#include <boost/bind.hpp>
#include <boost/function.hpp>

class Foo {
public:  
  typedef boost::function<int(int)> Boost_Fun;
  Boost_Fun fun_;
  int square(int a) {return a*a;}
  void test(int a, Boost_Fun f){
    std::cout<<"test("<<a<<")"<<f(a)<<std::endl;
  }
};
int _tmain(int argc, _TCHAR* argv[])
{
  Foo foo;
  Foo::Boost_Fun f = boost::bind(&Foo::square, &foo, _1);
  foo.test(4, f);
    return 0;
}

转载于:https://www.cnblogs.com/luhouxiang/archive/2012/08/14/2638369.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值