在C ++ 14中使用auto作为返回值和参数类型 [英] Use of auto as return and parameters type in C++14

查看:96
本文介绍了在C ++ 14中使用auto作为返回值和参数类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Bjarne Stroustrup的第四版(C ++编程语言)中,我们读到:

In the 4th edition of Bjarne Stroustrup book (The C++ programing language) we read that:


使用auto,我们避免了冗余和写长类型名称。这在泛型编程中尤其重要,在泛型编程中,程序员可能很难知道对象的确切类型,并且类型名称可能很长(第4.5.1节)。

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";

}

该程序的标准输出(与-std = C编译++ 14):

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

0
0.67

我想知道为什么即使乘法函数的返回类型是自动的,我也得到了带有c和d变量的不同结果(类型)。

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

编辑:
我的GCC版本: gcc版本5.4.0 20160609

推荐答案

首先,您的代码使用 gcc扩展名,即自动功能参数

To start with, your code makes use of gcc extension, namely auto function parameters.

我猜想您的 gcc 版本无法正常使用该扩展名,并提供了错误的结果(使用 gcc 7.1 我的 0.67 0.67 甚至使用自动参数)。

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).

在标准 C ++ 中重写函数的正常方法是应用模板:

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.

这篇关于在C ++ 14中使用auto作为返回值和参数类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆