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;
}
It all depends on the assumptions that you can do about the type.
template <typename T> T sum( T a, T b, T c = T() ) { return a+b+c; }
template <typename T> T sum2( T a, T b, T c = T(5) ) { return a+b+c; }
The first case, it only assumes that T is default constructible. For POD types that is value inititalization (IIRC) and is basically 0, so sum( 5, 7 ) will call sum( 5, 7, 0 ).
In the second case you require that the type can be constructed from an integer. For integral types, sum( 5, 7 ) will call sum( 5, 7, int(5) ) which is equivalent to sum( 5, 7, 5 ).
T at all, which would be fine as long as one passes an explicit argument.Yes!
However you should at least have an idea about what T could be or it's useless.
You can't set the default value of template parameters for functions, i.e. this is forbidden:
template<typename T=int> void f(T a, T b);