Using auto return and parameter type in C ++ 14

In the fourth edition of Bjarne Stroustrup's book (C ++ Programming Language) we read that:

By using auto we avoid redundancy and write long type names. This is especially important in generic programming, where the particular type of an object can be difficult for the programmer and the type names can be quite long (§4.5.1).

So, to understand the importance of this type. I made this little test program:

#include <iostream>

/*-----------------------------*/
auto multiplication(auto a, auto b)
{
    return a * b;
}


int main()
{
  auto c = multiplication(5,.134);
  auto d = 5 * .134;
  std::cout<<c<<"\n"<<d<<"\n";

}

      

Step of this program (compiled with -std = C ++ 14):

0
0.67

      

I am wondering why I have different results (types) with variables c and d, even if the return type of the multiplication function is auto.

EDIT: My GCC version:gcc version 5.4.0 20160609

+3


source to share


2 answers


To begin with, your code uses the gcc extension , namely the parameters of the automatic function.

I am assuming that your version of gcc is not working with the extension correctly and is giving the wrong output (with gcc 7.1 I have it 0.67 0.67

even using automatic parameters).

The usual way to rewrite your function in standard C ++ is to use templates:



template<typename T, typename U>
auto multiplication(T a, U b)
{
    return a * b;
}

      

and give the compiler an inference of the return type.

+6


source


Let's start with Bjarne Stroustrup in his fourth edition of his original book The C ++ Programming Language does not apply to use auto

as shown in the sample code. But instead of the standard use auto

specifier
like:

  • Variable specifier, where their type will be inferred by its initializer (for example auto i = 0;

    ).
  • A specifier for the return type of a function, where it will be inferred from its return type or from its return statement.

    auto foo(int a, int b) {return a + b; }



In your example, you are referring to use auto

as a placeholder as suggested by the C ++ Extension for Concepts (N4674) proposal. Unfortunately, this is not standard C ++ yet. This should have been accepted in C ++ 17, but it hasn't. The hopes are now growing for C ++ 20. However, use auto

as provided by GCC as an extension. Work on C ++ concepts for GCC started very early, even before C ++ 11. At some point, work on concepts was abandoned and then relaunched under a different name, namely Concepts Lite. Support was rather fragile back then (eg GCC version 5.4). So what you are experiencing is a GCC bug. Later versions of GCC have fixed this bug.

+3


source







All Articles