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;
}
You cannot give default arguments to the same template parameters in different declarations in the same scope. The compiler will not allow the following example: template<class T = char> class X; template<class T = char> class X { };
Can default arguments be used with the template class? Explanation: The template class can use default arguments.
A template argument for a template template parameter is the name of a class template. When the compiler tries to find a template to match the template template argument, it only considers primary class templates. (A primary template is the template that is being specialized.)
Template argument deduction doesn't work that way -- you can't deduce the type of an argument from a defaulted value. In C++11, you can however specify a default template argument:
template <typename Val, typename Fn = Val(&)(Val const &)>
Val Apply(const Val& v, Fn fn = Identity<Val>)
{
return fn(v);
}
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