13.3 Default Function Template Arguments

Ru-Brd

When templates were originally added to the C++ language, explicit function template arguments were not a valid construct. Function template arguments always had to be deducible from the call expression. As a result, there seemed to be no compelling reason to allow default function template arguments because the default would always be overridden by the deduced value.

Since then, however, it is possible to specify explicitly function template arguments that cannot be deduced. Hence, it would be entirely natural to specify default values for those nondeducible template arguments. Consider the following example:

 template <typename T1, typename T2 = int>  T2 count (T1 const& x);  class MyInt {   };  void test (Container const& c)  {      int i = count(c);      MyInt = count<MyInt>(c);      assert(MyInt == i);  } 

In this example, we have respected the constraint that if a template parameter has a default argument value, then each parameter after that must have a default template argument too. This constraint is needed for class templates; otherwise , there would be no way to specify trailing arguments in the general case. The following erroneous code illustrates this:

 template <typename T1 = int, typename T2>  class Bad;  Bad<int>* b;  // Is the given  int  a substitution for  T1  or for  T2  ?  

For function templates, however, the trailing arguments may be deduced. Hence, there is no technical difficulty in rewriting our example as follows :

 template <typename T1 = int, typename T2>  T1 count (T2 const& x);  void test (Container const& c)  {      int i = count(c);      MyInt = count<MyInt>(c);      assert(MyInt == i);  } 

At the time of this writing the C++ standardization committee is considering extending function templates in this direction.

In hindsight, programmers have also noted uses that do not involve explicit template arguments. For example:

 template <typename T = double>  void f(T const& = T());  int main()  {      f(1);  // OK: deduce  T = int      f<long>(2);  // OK:  T = long  ; no deduction  f<char>();  // OK: same as  f<char>(' 
 template <typename T = double> void f(T const& = T()); int main() { f(1);  // OK: deduce  T = int f<long>(2);  // OK:  T = long  ; no deduction  f<char>();  // OK: same as  f<char>('\0'); f();  // Same as  f<double>(0.0); } 
'); f(); // Same as f<double>(0.0); }

Here a default template argument enables a default call argument to apply without explicit template arguments.

Ru-Brd


C++ Templates
C++ Templates: The Complete Guide
ISBN: 0201734842
EAN: 2147483647
Year: 2002
Pages: 185

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net