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) << ' ';
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 type is called T, which can take on any type that supports the add operator). Instead of returning an auto, which would not state the output type, we return a type T. Although T is not defined here as it represents any type, it does tell the user of the API that any type we input into this function will also be returned by the function. This same logic is used heavily in the C++ standard library. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset