© Mikael Olsson 2020
M. OlssonC++20 Quick Syntax Referencehttps://doi.org/10.1007/978-1-4842-5995-5_28

28. Templates

Mikael Olsson1 
(1)
Hammarland, Finland
 

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

Function Templates

This example 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 typename and the name of the template type parameter, both enclosed between angle brackets. ...

Get C++20 Quick Syntax Reference: A Pocket Guide to the Language, APIs, and Library now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.