[Home]
[Edit this page]
[Recent Changes]
[Special Pages]
[Help]
CppTemplateFunction
Note that all these functions are in the STL (the latter is called accumulate) and are all templated.
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
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
- Bjarne Stroustrup's C++ glossary. http://www.research.att.com/~bs/glossary.html
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
