c++ - 将函数模板传递给其他函数

标签 c++ templates function-pointers

假设我有一个函数可以对任意容器类型 (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 );
}

关于c++ - 将函数模板传递给其他函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9308749/

相关文章:

c++ - 为什么 std::string 不采用空指针?

c++ - decltype 与具有默认参数的函数模板会产生困惑的结果(一个有趣的问题或 gcc 的错误)

delphi - 如何获取方法指针指向的方法的名称?

c++ - 是否有用于 C++ 的 Python StringIO/StringIO 之类的东西?

c++ - 为什么 Scott Meyers 建议更喜欢 `iterator` 而不是 `const_iterator`

c++ - 哪个更耗内存?矩阵或三角函数变换

c++ - 模板特化类函数

c++ - 连接超过1个节点的子列表时,链表合并合并的C++实现失败

c - void* 函数指针数组转换

c - 使用接口(interface)时函数指针转换或参数转换