【问题标题】:boost::function with function templates带有函数模板的 boost::function
【发布时间】:2013-07-09 05:02:48
【问题描述】:
#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 与函数模板一起使用?

【问题讨论】:

  • fun 没有被声明也无济于事。
  • 'fun' 是拼写错误,意图是 'Print'

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


【解决方案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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-30
    • 1970-01-01
    • 1970-01-01
    • 2019-12-13
    • 1970-01-01
    • 1970-01-01
    • 2010-12-27
    相关资源
    最近更新 更多