© Mikael Olsson 2018
Mikael OlssonC++17 Quick Syntax Referencehttps://doi.org/10.1007/978-1-4842-3600-0_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 class and the name of the template parameter, both enclosed between angle brackets. ...

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

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.