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.
}
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 );
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With