c++templatesdefault-valuedefault-arguments

How to specify a default function argument with a template parameter type T


Is it possible to define the default value for variables of a template function in C++?

Something like below:

template<class T> T sum(T a, T b, T c=????)
{
     return a + b + c;
}

Solution

  • Try this:

    template<class T> T sum(T a, T b, T c=T())
    {
         return a + b + c;
    }
    

    You can also put in T(5) if you are expecting an integral type and want the default value to be 5.