2.2 Argument Deduction

Ru-Brd

When we call a function template such as max() for some arguments, the template parameters are determined by the arguments we pass. If we pass two int s to the parameter types T const& , the C++ compiler must conclude that T must be int . Note that no automatic type conversion is allowed here. Each T must match exactly. For example:

 template <typename T>  inline T const& max (T const& a, T const& b);   max(4,7)  // OK:  T  is  int  for both arguments  max(4,4.2)  // ERROR: first  T  is  int  , second  T  is  double 

There are three ways to handle such an error:

  1. Cast the arguments so that they both match:

     max(static_cast<double>(4),4.2)  // OK  
  2. Specify (or qualify) explicitly the type of T:

     max<double>(4,4.2)  // OK  
  3. Specify that the parameters may have different types.

For a detailed discussion of these topics, see the next section.

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