concept auto in category c++

appears as: uto
Functional Programming in C++

This is an excerpt from Manning's book Functional Programming in C++.

The capability to pass functions as arguments to another function, and to have functions that return new functions (or, more precisely, things that look like functions, as we’ll discuss in chapter 3), made even the first standardized version of C++ an FP language. C++11, C++14, and C++17 introduced quite a few features that make writing programs in the functional style much easier. The additional features are mostly syntactic sugar—but important syntactic sugar, in the form of the auto keyword and lambdas (discussed in chapter 3). These features also brought significant improvements to the set of standard algorithms. The next revision of the standard is planned for 2020, and it’s expected to introduce even more FP-inspired features such as ranges, concepts, and coroutines, which are currently Technical Specifications.

The following example has an integer named answer and two functions ask1 and ask2. Both functions have the same body; they return answer. But their return types are specified differently. The first function returns a value whose type is automatically deduced, and the second function returns a const-ref to a type that’s automatically deduced. The compiler will check the type of the variable you pass to the return statement, which is int, and replace the keyword auto with it:

auto ask(bool flag)
{
    if (flag) return 42;
    else      return std::string("42");    #1  
}

#1   Error: inconsistent deduction for ‘auto’: ‘int’ and then ‘std::string’