O'Reilly logo

C++ Quick Syntax Reference by Mikael Olsson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

CHAPTER 27

image

Templates

Templates provide a way to make a class or function operate with different data types without having to rewrite the code for each type.

Function templates

The example below shows a function that swaps two integer arguments.

void swap(int& a, int& b){  int tmp = a;  a = b;  b = tmp;}

To convert this method into a function template that can work with any type the first step is to add a template parameter declaration before the function. This declaration includes the template keyword followed by the keyword class and the name of the template parameter, both enclosed between angle brackets. The name of the template parameter ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required