c++ - 在 C++14 中使用 auto 作为返回和参数类型

标签 c++ c++14

在 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/

相关文章:

c++ - 从C++连接MySQL : error LNK2001: unresolved external symbol

c++ - rapidxml:如何遍历节点?遗漏了最后一个 sibling

c++ - enable_if 的奇怪行为

c++ - 线程抛出异常后出现"Bad promise"错误

c++ - 模板参数和 std::function 参数的推导

c++ - 字符串类中未声明的标识符

c++ - 使用 std::list<std::string> 时 std::string 的内存泄漏

c++ - UCI 种子数据集上的 CGAL::Delaunay_d C++: “EXC_BAD_ACCESS”

c++ - lambda表达式移动捕获的时机

c++ - 带有 std::function 的模板不直接匹配 lambda