在 Bjarne Stroustrup 的书(C++ 编程语言)第 4 版中,我们读到:
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).
所以,要明白这个类型的重要性。我做了这个小测试程序:
#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";
}
这个程序的标准输出(用-std=C++14编译):
0
0.67
我想知道为什么即使乘法函数的返回类型是 auto,c 和 d 变量也会得到不同的结果(类型)。
编辑:
我的 GCC 版本:gcc version 5.4.0 20160609
最佳答案
首先,您的代码使用了 gcc extension ,即自动函数参数。
我猜你的 gcc 版本不能正确地使用扩展并提供不正确的结果(使用 gcc 7.1 我有 0.67 0.67
甚至使用自动参数)。
在标准 C++ 中重写函数的正常方法是应用模板:
template<typename T, typename U>
auto multiplication(T a, U b)
{
return a * b;
}
并让编译器推断返回类型。
关于c++ - 在 C++14 中使用 auto 作为返回和参数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45001066/