I want to create a method that takes some parameter T, boolean function and does something with it (let's say print it if func(param) is true). The problem I have encountered is that:
when you write code without templates, both following examples work:
static bool is_even(int i) {
return i % 2 == 0;
}
void f(const int &d, bool (*f) (int)) {
cout << (f(d) ? "true" : "false");
}
//void f(const int &d, std::function<bool(int)> f) {
// cout << (f(d) ? "true" : "false");
//}
f(10, [](int e) -> bool { return e % 2 == 0; });
f(10, is_even);
even if I comment out second function and comment first, it would still work. But when I add template like this:
template<typename T>
void f(const T &d, bool (*f) (T)) {
cout << (f(d) ? "true" : "false");
}
Or this
template<typename T>
void f(const T &d, std::function<bool(T)> f) {
cout << (f(d) ? "true" : "false");
}
It says
no instance of function template "f" matches the argument list argument types are: (int, lambda []bool (int e)->bool)
If I use std::function, it also says
no instance of function template "f" matches the argument list argument types are: (int, bool (int i))
So the question is: How can I make this template work both with functions and with lambdas?
edit: I think I initially gave less information than needed. The thing is that I want to overload an operator several times with different functions like this:
template<typename T>
vector<T> operator|(const vector<T> &vec, void (*f) (T)) {
// ...
}
template<typename T>
vector<T> operator|(const vector<T> &vec, bool (*f) (T)) {
// ...
}
template<typename TIn, typename TOut>
vector<TOut> operator|(const vector<TIn> &vec, TOut (*f) (TIn)) {
// ...
}