问题
In the 4th edition of Bjarne Stroustrup book (The C++ programing language) we read that:
Using auto , we avoid redundancy and writing long type names. This is especially important in generic programming where the exact type of an object can be hard for the programmer to know and the type names can be quite long (§4.5.1).
So, to understand the importance of this type. I made this small 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";
}
The stdout of this program (compiled with -std=C++14):
0
0.67
I am wondering why I got different results (types) with c and d variables even if the return type of multiplication function is auto.
EDIT:
My GCC version: gcc version 5.4.0 20160609
回答1:
To start with, your code makes use of gcc extension, namely auto function parameters.
I guess your gcc version does not work with the extension properly and provides an incorrect result (with gcc 7.1 I have 0.67 0.67 even using auto parameters).
The normal way to rewrite your function in a standard C++ is to apply templates:
template<typename T, typename U>
auto multiplication(T a, U b)
{
return a * b;
}
and let the compiler to deduce return type.
回答2:
To start with Bjarne Stroustrup in his 4th edition of his seminal book "The C++ Programming Language" doesn't refer to the use of auto as rendered in your code example. But rather to the standard use of the auto specifier as:
- Specifier for variables where their type is going to be deduced by its initializer (e.g.,
auto i = 0;). Specifier for function's return type where it's going to be deduced by its trailing return type or from its return statement.
auto foo(int a, int b) {return a + b; }
In your example you're referring to the use of auto as a placeholder as suggested by C++ extensions for Concepts (N4674) proposal. Unfortunately, this is not standard C++ yet. It was to be accepted in C++17 but it didn't make it. Hopes now rise for C++20. However, use of auto like that is provided by GCC as an extension. Work on C++ concepts for GCC started very early, it even predates the advent of C++11. At some point work on concepts was abandoned and then restarted under another name namely Concepts Lite. Support back then was pretty unstable (e.g., GCC version 5.4). Thus, what you're experiencing is a GCC bug. In more recent versions of GCC this bug has been corrected.
来源:https://stackoverflow.com/questions/45001066/use-of-auto-as-return-and-parameters-type-in-c14