Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specifying default value for template function argument

Tags:

c++

templates

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;
}
like image 335
Andrey Avatar asked Aug 20 '12 12:08

Andrey


People also ask

Can we specify default value for template arguments?

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 argument be used with the template class?

Can default arguments be used with the template class? Explanation: The template class can use default arguments.

How do you use template arguments in C++?

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.)


1 Answers

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);
}
like image 134
Kerrek SB Avatar answered Sep 28 '22 07:09

Kerrek SB