c++ - 带有函数模板的 boost::function

标签 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 与函数模板一起使用?

最佳答案

让仿函数成为模板参数会更简单:

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);

关于c++ - 带有函数模板的 boost::function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17540300/

相关文章:

c++ - 为什么 shared_ptr 没有虚拟析构函数? (我该如何解决这个问题?)

c# - unsigned char * - 等效的 C#

c++ - 在 Boost zip 迭代器上使用 C++17 并行执行算法时,为什么会出现 MSVC 错误?

c++ - Qt:最小化子小部件的应用程序

c++ - 锁定取消引用的互斥量是不好的行为吗?

c# - 你能在运行时使用 C# 实例化模板类吗

c++ - 采用 std::vector 或 std::array 的模板函数

c++ - 具有模板化继承的纯虚函数

c++ - Boost 1.53.0 - 构建 VC++11 时出现 LNK1104 错误

c++ - Boost Serialization Binary Archive 提供不正确的输出