游戏开发论坛

 找回密码
 立即注册
搜索
查看: 4524|回复: 0

boost之5.function

[复制链接]

56

主题

94

帖子

98

积分

注册会员

Rank: 2

积分
98
发表于 2010-8-14 20:49:00 | 显示全部楼层 |阅读模式
本篇主要说明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 =
∑
    std::cout<<"1+2=:?"<<sum_ptr(1,2);
    system(&quotAUSE");
    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
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

作品发布|文章投稿|广告合作|关于本站|游戏开发论坛 ( 闽ICP备17032699号-3 )

GMT+8, 2024-4-28 19:19

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表