boost :: function with function templates

时间:2013-07-09 05:02:48

标签: c++ templates boost boost-function function-templates

#include <vector>
#include <iostream>
#include "boost/function.hpp"


template <class T1, class T2, class T3>
static void
FOREACH (T1 cont, boost::function<T2(T3)> callback) {
    typename T1::iterator it = cont. begin ();
    for ( ; it != cont. end(); it++ ) {
        callback (*it);
    }
}


static void
Print (int number) 
{
    std:: cout << number << std:: endl;
}


int  main ()
{
    std:: vector<int> vec;
    for ( int i=1; i <= 10; ++i ) vec. push_back (2*i);

    FOREACH ( vec, fun );

    return 0;
}

为什么上面的代码不能编译? 如果我创建如下的专用版本,它可以正常工作。

static void
FOREACH (std:: vector<int> cont, boost::function<void(int)> callback) {
    std:: vector<int>:: iterator it = cont. begin ();
    for ( ; it != cont. end(); it++ ) {
        callback (*it);
    }
}

请有人告诉我如何在功能模板中使用boost :: function?

1 个答案:

答案 0 :(得分:1)

将仿函数作为模板参数会更简单:

template <class T1, class F>
static void FOREACH (T1 cont, F callback) {
    typename T1::iterator it = cont.begin();
    for ( ; it != cont. end(); it++ ) {
        callback (*it);
    }
}

如果您传递一个实际存在的兼容可调用实体,这将有效。当然,使用std::for_each

会更容易
#include <algoritm>

...

std::for_each(vec.begin(), vec.end(), Print);