boost function和bind的使用

原本是打算在一个函数中实现图像的基本读入与写出,然后传入函数对象进行处理,那么只用对不同的操作实现不同的函数对象就可以了。然而实现的过程中发现不可行,主要原因是传入的函数对象是一个模板函数,但是函数的实例化却在函数内部。尽管没能弄成,但是昨天折腾了一天,对boost库中的bind和function总算有点了解,在此记录一下吧。

#include <boost\function.hpp>
#include <boost\bind.hpp>
#include <vector>
#include <iostream>

    // template function, using with boost::bind
    template <typename T>
T add(T a, T b)
{
    return a+b;
}

// using with boost::bind or boost::function<int (int)> fn;
template <typename T>
T add1(T a)
{
    return a+10;
}

// functor
template <typename T>
struct Adds
{
    T operator() (T a, T b) {return a+b;}
};

//  how to use the function
// void process(boost::function<double (T)> pred) this is not allowed
template <typename T>
void process(T pred)
{
    //
    std::vector<int> x;
    for (int i=0; i<10; ++i)
    {
        x.push_back(pred(i));
        //        x.push_back(i);
    }

    //    for_each(x.begin(), x.end(), pred);

    for (int i=0; i<10; ++i)
    {
        std::cout << x.at(i) <<"\n";
    }
}

void test1()
{

    boost::function<int (int)> fn;
    fn = add1<int>;
    process( fn);
    process( boost::bind<int>(add1<int>, _1));

    process(boost::bind<int>(add<int>,_1,1000));

    process(boost::bind<int>(Adds<int>(), _1, 100));
}

 

本文中暂时并未考虑效率神马的,没有把全局对象换成ref。bind的主要目的还是应用对函数的参数进行组合等操作,以及构建function对象。

process( boost::bind<int>(add1<int>, _1));

boost::function<int (int)> fn;
fn = add1<int>;
process( fn);

是等价的,但下面的相当于多创建了一个function对象,也就是这里的fn。

在调用模板函数的时候,一定要知道他的实例化对象,也就是<int>,这样才能在编译期生成对应的对象。对于function对象来说,函数的返回值和参数对象决定了其自身的对象类型。而bind也需要确定返回类型,此外,第二例中bind将add函数的参数减少了一个,因此不用实例化1。

第三种方法是实现functor,在我看来这是一种很灵活的方法,好像说这种方法可以内联(function paased as template argument中有阐述,原谅我英语不好)。在http://www.cnblogs.com/oomusou/archive/2007/05/12/744000.html文中他说还可以利用对象构建的方式初始化,比较有意思。那篇文章中说的是利用for_each,我试图尝试,发现该函数无返回值,而连接中的博客所有的调用基本上也是void f(…);的方式。

关于模板函数是否能作为参数传入的,Ben的说法是,void process(boost::function<double (T)> pred)这种申明方法是不可行的,因为你要为模板函数的对象T实例化,又要对函数方法pred实例化。因此其采用了方法是将对象类型固定,然后将函数方法作为模板。

int addx(int a, int b);
template <class Func>
int do_fun(Func f, int a, int b)
{
return f(a,b);
}

使用方法如下:
process(boost::bind<int>(do_fun<boost::function<int (int, int)> >, addx, _1, 10000));

当然,可以实现相应的sub运算等。但是这样的方法仍然很无力,对于不同的对象我岂不要强制转换。那么我将函数方法进行模板化,同时将函数类型同时进行模板化呢?类似C++ template p46页中的方法,答案是编译器发生内部错误。这个问题到这里为止啦,毕竟我只是用而已

原文链接: https://www.cnblogs.com/honbo/archive/2013/01/26/2877656.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    boost function和bind的使用

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/76886

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月9日 下午5:43
下一篇 2023年2月9日 下午5:43

相关推荐