Skip to Content
Advanced C++ Programming Cookbook
book

Advanced C++ Programming Cookbook

by Dr. Rian Quinn
January 2020
Intermediate to advanced
454 pages
11h 25m
English
Packt Publishing
Content preview from Advanced C++ Programming Cookbook

Example 9

Example 9 demonstrates the principle of least surprise as follows:

#include <iostream>template <typename T>T add(T a, T b){ return a + b; }int main(void){    std::cout << "The answer is: " << add(41, 1) << '\n';    return 0;}

As shown in the preceding example, we are demonstrating a more appropriate way to uphold the principle of least surprise while simultaneously supporting generic programming. Generic programming (also called template meta-programming or programming with C++ templates) provides the programmer with a way to create an algorithm without stating the types that are being used in the algorithm. In this case, the add function doesn't dictate the input type, allowing the user to add two values of any type (in this case, the ...

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

Modern C++ Programming Cookbook

Modern C++ Programming Cookbook

Marius Bancila

Publisher Resources

ISBN: 9781838559915Supplemental Content