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++

Substitution failure

Once we have deduced the template parameter types, type substitution is a purely mechanical process:

template <typename T> T* f(T i, T& j) { j = 2*i; return new T(i); }int i = 5, j = 7;const int* p = f(i, j);

In this example, the T type can be deduced from the first argument as int. It can also be deduced from the second argument, also as int. Note that the return type is not used for the type deduction. Since there is only one possible deduction for T, we now proceed to substitute T with int every time we see T in the function definition:

int* f(int i, int& j) { j = 2*i; return new int(i); }

Not all types, however, are created equal, and some allow more liberties than others. Consider this code:

template <typename T> ...
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