[Home]  [Edit this page]  [Recent Changes]  [Special Pages]  [Help
CppTemplateFunction

(C++) Template function

A template function is a "function parameterized by types, values, or templates. The function to be generated from a template function can usually be deduced from the function arguments in a call" [1].

//Sum two values of equal data type
template <class T>
T sum(const T& value1, const T& value2)
{  
  return value1 + value2;
}
template <class T>
T swap(T& value1, T& value2)
{  
  const T temp = value1;
  value1 = value2;
  value2 = temp;
}
//Sum a vector of any type
template <class T>
T sum(const std::vector<T>& v)
{  
  const int size = v.size(); //A vector's size is always of type int
  T mySum = 0.0;
  for(int i=0; i<size; ++i); //An index counter is always of type int
  {
    mySum+=v[i];
  }
  return mySum;
}


Note that all these functions are in the STL (the latter is called accumulate) and are all templated.

Code links

Reference



last edited (November 18, 2006) by bilderbikkel, Number of views: 1165, Current Rev: 2 (Diff)

[Edit this page]  [Page history]  [What links here]  [Discuss this topic]  [Printer Friendly]  

Members

Username:

Password:


Register
Forgot Password?




Programmers Heaven - for .NET, Java, C/C++ and WEB Developers!
© 1996-2008 Community Networks Ltd. All rights reserved. Reproduction in whole or in part, in any form or medium without express written permission is prohibited. Violators of this policy may be subject to legal action. Please read Terms Of Use and Privacy Statement for more information. Development by Tore Nestenius at .NET Consultant - Synchron Data.