Skip to Content
Hands-On Design Patterns with C++
book

Hands-On Design Patterns with C++

by Fedor G. Pikus
January 2019
Intermediate to advanced
512 pages
14h 5m
English
Packt Publishing
Content preview from Hands-On Design Patterns with C++

Function templates

To use a function template to generate a function, we have to specify which types should be used for all template type parameters. We can just specify the types directly:

template <typename T>T half(T x) { return x/2; }int i = half<int>(5);

This instantiates the half function template with the int type. The type is explicitly specified; we could call the function with an argument of another type, as long as it is convertible to the type we requested:

double x = half<double>(5);

Even though the argument is an int, the instantiation is that of half<double>, and the return type is double. The integer value 5 is implicitly converted to double.

Even though every function template can be instantiated by specifying all its type ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Structural Design Patterns in Modern C++

Structural Design Patterns in Modern C++

Umar Lone

Publisher Resources

ISBN: 9781788832564Supplemental Content