Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass a function template to other function

Suppose I have a function that does something on an arbitrary container type (C++11):

template<class containerType>
void bar( containerType& vec ) {

        for (auto i: vec) {
                std::cout << i << ", ";
        }

        std::cout << '\n';
}

I can call this function from another function like this:

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

Now suppose I have different functions just like bar, and I want to pass one of these functions to foo, then foo would look something like this:

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

However, calling foo like this:

foo(bar);

does not work (pretty clear, since bar is not a function but a function template). Is there any nice solution to this? How must I define foo to make this work?

EDIT: here is a minimal compileable example, as demanded in the comments...

#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.
}
like image 224
fdlm Avatar asked Dec 27 '22 05:12

fdlm


2 Answers

Online demo at http://ideone.com/HEIAl

This allows you to do foo(bar). Instead of passing in a template-function or a template-class, we pass in a non-template class that has a template-member-function.

#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 );
}
like image 110
Aaron McDaid Avatar answered Dec 29 '22 18:12

Aaron McDaid


If you know that foo works with a vector of int, you can pass bar< std::vector<int> > function.

A reasonable solution would be for the module that defines foo to also define typedef for the container used. Then you don't even need bar to be a template.

like image 29
Juraj Blaho Avatar answered Dec 29 '22 19:12

Juraj Blaho