Could you explain why the following code doesn’t compile? An obvious workaround is to add a 1-argument overload of Apply, is there a simpler one?
template <typename T>
T Identity(const T& i_val)
{
return i_val;
}
template <typename Val, typename Fn>
Val Apply(const Val& v, Fn fn = Identity<Val>)
{
return fn(v);
}
int main() {
Apply(42); // error: no matching function for call to 'Apply(int)'
Apply(42, Identity<int>); // OK
return 0;
}
Looking up the function to call consists of:
1. creating the set of candidates, which includes template argument deduction
2. determining the best overload
If I understand the standard correctly, only actual function arguments (i.e., not the default ones) take part in deducing the template arguments. Therefore from the argument
42, the only thing the compiler can infer is thatVal=int. The overload does not enter the candidate set and the default argument is never looked at.