I want my template function
template<class function>
int probe(function call = [] (int a, int b) { return a+b; })
{
return call(10, 10);
}
to be able to receive pointers to functions and invoke this function later. This excerpt is correct and the compiler does not complain on errors. Let's consider the such program
#include <iostream>
#include <string>
template<class function>
int probe(function call = [] (int a, int b) { return a+b; })
{
return call(10, 10);
}
int main()
{
std::cout << probe([](int a,int b){ return a-b;});
}
The program outputs what I've expected: zero. However, I explicitly denoted for this call what a function I am passing - I mean about this lambda-expression in the parentheses [](int a,int b){ return a-b;}
. That's fine until I pass nothing - the call std::cout << probe();
is incorrect, however I've expected that the function will use default function function call = [] (int a, int b) { return a+b; }
. So, how do I call the function that instance of this function will use default lambda-expression in the declaration?
Default function arguments don't contribute to template argument deduction. The compiler can't deduce function
when no function argument is given explicitly, and so the call site cannot be matched to any function to call.
One pretty straightforward way to get your example to work, is to overload instead.
template<class function>
int probe(function call)
{
return call(10, 10);
}
inline int probe()
{
return probe([] (int a, int b) { return a+b; });
}