C++ template

Introduction

Templates are mechanisms to support the so-called generic programming.

Generic broadly means we can define a function or a class without worrying about what types it accepts.

We define those functions and classes using some generic type.

And when we instantiate them, we use a concrete type.

So, we can use templates when we want to define a class or a function that can accept almost any type.

We define a template by typing:

template <typename T> 
// the rest of our function or class code 

Which is the same as if we used:

template <class T> 
// the rest of our function or class code 

T here stands for a type name. Which type? Well, any type. Here T means, for all types T.

Let us create a function that can accept any type of argument:

#include <iostream> 

template <typename T> 
void myfunction(T param) 
{ 
    std::cout << "The value of a parameter is: " << param; 
} 

int main() /*from w w w. j  ava 2 s .  c o  m*/
{ 

} 

To instantiate a function template, we call a function by supplying a specific type name, surrounded by angle brackets:

#include <iostream> 

template <typename T> 
void myfunction(T param) 
{ 
    std::cout << "The value of a parameter is: " << param; 
} 

int main() /*from  w  w  w  .ja  v  a  2  s .c om*/
{ 
    myfunction<int>(123); 
    myfunction<double>(123.456); 
    myfunction<char>('A'); 
} 

We can think of T as a placeholder for a specific type, the one we supply when we instantiate a template.

So, in place of T, we now put our specific type.

This way, we can utilize the same code for different types.




PreviousNext

Related