January 2020
Intermediate to advanced
454 pages
11h 25m
English
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 ...