Cpper
C/C++高级工程师 Android高级软件工程师 IT集成工程师 音频工程师 熟悉c,c++,java,c#,py,js,asp等多种语言 程序猿
本篇主要说明boost function的使用例子
设计头文件:
#include <boost/function.hpp>

基本的function对象例子
boost::function<int(const char*,&int)> f;
代码该函子对应的函数其返回值为int类型,她有个2个参数分别为const char*和&int类型
一个简单的例子如下所示:
#include <iostream>
#include 
<boost/function.hpp>

inline 
int Sum(const int a,const int b)
{
    
return a + b;    
}

int main()
{   
    boost::function
<int(const int,const int)> sum_ptr;
    sum_ptr 
= &Sum;
    std::cout
<<"1+2=:?"<<sum_ptr(1,2);
    system(
"PAUSE");
    
return EXIT_SUCCESS;
}
如果对应的函数为类的成员函数则其使用例子可参考下面的说明:
#include <iostream>
#include 
<boost/function.hpp>
#include 
<functional>

struct Adder 
{
    Adder(
int val):value(val){}
    
int Add(int x){return x*value;}
    
int value;
};

int main()
{   
    
//! 对应函数返回值int参数为int
    boost::function<int(int)>f;
    Adder add(
7);
    
//! 绑定成员函数到boost::function<>
    f = std::bind1st(std::mem_fun(&Adder::Add),&add);
    std::cout
<<f(5)<<std::endl; 

    
    system(
"PAUSE");
    
return EXIT_SUCCESS;
}
对于仿函子则可以这样做:
#include <iostream>
#include 
<boost/function.hpp>
#include 
<functional>

struct Div 
{
    
float operator()(int x, int y)const 
    {    
       
return((float)x)/y; 
    }
};

int main()
{   
    
//! 2
    boost::function<float(int,int)> div;
    div 
= Div();
    std::cout
<<div(1,2)<<std::endl;
    
    system(
"PAUSE");
    
return EXIT_SUCCESS;
}
//! ccsdu2004

posted on 2010-08-14 18:42 ccsdu2009 阅读(416) 评论(0)  编辑 收藏 引用 所属分类: boost库等

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理