gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 11:52:32 25 4
gpt4 key购买 nike

#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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com