将函数模板传递给其他函数

Pass a function template to other function

本文关键字:其他 函数 函数模板      更新时间:2023-10-16

假设我有一个函数对任意容器类型(C++11)执行某些操作:

template<class containerType>
void bar( containerType& vec ) {
        for (auto i: vec) {
                std::cout << i << ", ";
        }
        std::cout << 'n';
}

我可以从另一个类似的函数调用这个函数:

void foo() {
        std::vector<int> vec = { 1, 2, 3 };
        bar(vec);
}

现在假设我有不同的函数,就像bar一样,我想把其中一个函数传递给foo,那么foo会看起来像这样:

template<class funcType>
void foo( funcType func ) {
    std::vector<int> vec = { 1, 2, 3 };
    func(vec);
}

然而,像这样调用foo:

foo(bar);

不起作用(很清楚,因为bar不是一个函数,而是一个函数模板)。有什么好的解决方案吗?我必须如何定义foo才能使其工作?

编辑:这是一个最小的可编译示例,正如评论中所要求的。。。

#include <iostream>
#include <vector>
#include <list>
template<class containerType>
void bar( containerType& vec ) {
        for (auto i: vec) {
                std::cout << i << ", ";
        }
        std::cout << 'n';
}
template<typename funcType>
void foo(funcType func) {
        std::vector<int> vals = { 1, 2, 3 };
        func(vals);
}
int main() {
        // foo( bar );  - does not work.
}

在线演示http://ideone.com/HEIAl

这允许您执行foo(bar)。我们没有传入模板函数或模板类,而是传入一个具有模板成员函数的非模板类。

#include <iostream>
#include <vector>
#include <list>
struct {
    template<class containerType>
    void operator() ( containerType& vec ) {
        for (auto i = vec.begin(); i!=vec.end(); ++i) {
                std::cout << *i << ", ";
        }
        std::cout << 'n';
    }
} bar;
template<typename funcType>
void foo(funcType func) {
        std::vector<int> vals = { 1, 2, 3 };
        func(vals);
}
int main() {
        foo( bar );
}

如果您知道foo使用int向量,那么您可以传递bar< std::vector<int> >函数。

一个合理的解决方案是,定义foo的模块也为所使用的容器定义typedef。那么您甚至不需要bar作为模板。

类似的东西?(没有完全清醒,可能会错过要点)

#include <iostream>
#include <vector>
#include <list>
struct Test{
template<class containerType>
static void apply( containerType& vec ) {
        for (auto it = vec.begin(); it != vec.end(); ++it) {
                std::cout << *it << ", ";
        }
        std::cout << 'n';
}
};
template<class FuncStruct>
void foo() {
        std::vector<int> vals;
        vals.push_back(1);
        FuncStruct::apply(vals);
}
int _tmain(int argc, _TCHAR* argv[])
{
    foo<Test>();
    return 0;
}