Example 8

Example 8 demonstrates the principle of least surprise as follows:

#include <iostream>

auto add(int a, int 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 how the use of auto, which tells the compiler to figure out what the return type of the function is automatically, does not uphold the principle of least surprise. Although auto is extremely helpful for writing generic code, its use should be avoided as much as possible when designing a library API. Specifically, for the user of the API to understand what the inputs and outputs of the API are, the user must read the API's implementation as auto does not specify the output type. 

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

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