Leon Anavi
IT Tips && Tricks

C/C++

Created: 04.11.2009 23:37 Last Modified: 04.11.2009 23:45 Views: 7358
Keywords: class, function, generic, template

Template Functions

Definition

A special C++ function which operates with generic types. Template functions are useful for common code intended to be use by multiple types without retyping it.

Syntax

template <class identifier> FunctionName;
template <typename identifier> FunctionName;

Example

The source code demonstrates a template function that returns the sum of two numbers and example usage with integer and float values.

Source Code

#include <iostream>

template<class GenericNumber> GenericNumber Add(GenericNumber nA, GenericNumber nB) throw()
{
        GenericNumber nRes = nA + nB;
        return nRes;
}

int main()
{
        int nInt1 = 10;
        int nInt2 = 6;
        int nIntRes = Add<int>(nInt1, nInt2);

        float nFl1 = 4.06;
        float nFl2 = 2.50;
        float nFlRes = Add<float>(nFl1, nFl2);

        std::cout << nInt1 << "+" << nInt2 << "=" << nIntRes << std::endl;
        std::cout << nFl1 << "+" << nFl2 << "=" << nFlRes << std::endl;
        return 0;
}

Output

[leon@localhost tempfunc]$ g++ main.cpp -Wall -o templatefunc
[leon@localhost tempfunc]$ ./templatefunc
10+6=16
4.06+2.5=6.56

Further Reading

Templates


  Home | About | Contact | Disclaimer | Sitemap © 2009-2022 Leon Anavi. All rights reserved.