11

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;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
MBZ
  • 26,084
  • 47
  • 114
  • 191

5 Answers5

12

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Scharron
  • 17,233
  • 6
  • 44
  • 63
7

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

Bill
  • 14,257
  • 4
  • 43
  • 55
David Rodríguez - dribeas
  • 204,818
  • 23
  • 294
  • 489
  • 3
    The default arguments are instantiated only if they are used. Which means one can put any crazy thing into them that wouldn't be compatible with `T` at all, which would be fine as long as one passes an explicit argument. – Johannes Schaub - litb Jul 21 '10 at 18:19
2

Yes you can define a default value.

template <class T> 
T constructThird()
{
    return T(1);
}

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

Unfortunately constructThird cannot take a and b as arguments.

computinglife
  • 4,321
  • 1
  • 21
  • 18
1

Yes, there just needs to be a constructor for T from whatever value you put there. Given the code you show, I assume you'd probably want that argument to be 0. If you want more than one argument to the constructor, you could put T(arg1, arg2, arg3) as the default value.

Phil Miller
  • 36,389
  • 13
  • 67
  • 90
0

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);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Tomaka17
  • 4,832
  • 5
  • 29
  • 38