4.2 Nontype Function Template Parameters

Ru-Brd

You can also define nontype parameters for function templates. For example, the following function template defines a group of functions for which a certain value can be added:

  // basics/addval.hpp  template <typename T, int VAL>  T addValue (T const& x)  {      return x + VAL;  } 

These kinds of functions are useful if functions or operations in general are used as parameters. For example, if you use the Standard Template Library (STL) you can pass an instantiation of this function template to add a value to each element of a collection:

 std::transform (source.begin(), source.end(),  // start and end of source  dest.begin(),  // start of destination  addValue<int,5>);  // operation  

The last argument instantiates the function template addValue() to add 5 to an int value. The resulting function is called for each element in the source collection source , while it is translated into the destination collection dest .

Note that there is a problem with this example: addValue<int,5> is a function template, and function templates are considered to name a set of overloaded functions (even if the set has only one member). However, according to the current standard, sets of overloaded functions cannot be used for template parameter deduction . Thus, you have to cast to the exact type of the function template argument:

 std::transform (source.begin(), source.end(),  // start and end of source  dest.begin(),  // start of destination  (int(*)(int const&)) addValue<int,5>);  // operation  

There is a proposal for the standard to fix this behavior so that the cast isn't necessary in this context (see [CoreIssue115] for details), but until then the cast may be necessary to be portable.

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