Reputation: 153
I have this method header:
void Find(const _T & v, int max, const function<bool(const _E &)> & filter)
I'm using std::function
because I need to accept function pointer, functor or lambda expression. I would like the filter to be optional, and default to function that always return true (nothing is filtered out) as default parameter. I've tried something like this:
#include <functional>
template <typename E>
bool alwaystrue(const E & e){ return true; }
template <typename T, typename E>
void Find(const T & v, int max,
const std::function<bool(const E &)> & filter = alwaystrue);
int main()
{
Find<int, int>(1, 2);
}
But this doesn't compile:
50016981.cpp: In function ‘void Find(const T&, int, const std::function<bool(const E&)>&) [with T = int; E = int]’:
50016981.cpp:11:24: error: cannot resolve overloaded function ‘alwaystrue’ based on conversion to type ‘const std::function<bool(const int&)>&’
Find<int, int>(1, 2);
^
I've also tried having the function inside my class but got a similar error.
Is there a problem combining with std::function
with templates? And if so, could you suggest how to do what I want? I want to avoid overloading the Find()
function (if possible) so I don't have duplicate code.
Upvotes: 0
Views: 2217
Reputation: 30824
You need to indicate which instantiation of alwaystrue
you want to use as your default, i.e. alwaystrue<E>
:
template <typename T, typename E>
void Find(const T& v, int max,
const std::function<bool(const E&)>& filter = alwaystrue<E>);
Upvotes: 2