关于auto作为参数类型,C++14标准有什么规定

What does the C++14 standard say regarding auto as argument type

本文关键字:标准 什么 C++14 auto 参数 类型 关于      更新时间:2023-10-16

让我们看看下面的代码:

#include <iostream>
class Test
{
private:
    int x;
public:
    Test(int _x) :
        x(_x)
    {
        std::cout << "Im being constructed" << std::endl;
    }
    int getx()
    {
        return this->x;
    }
    friend std::ostream& operator<<(std::ostream& os, Test& other)
    {
        os << other.getx();
        return os;
    }
};
auto func(auto x)
{
    std::cout << x << std::endl;
    return x.getx();
}
int main()
{
    auto y = func(20);
    return 0;
}

编译器如何决定(20)应该是int对象还是Test对象?Test的构造函数不是显式的,那么标准对它有什么规定呢?

因此,尽管gcc允许auto作为函数中的参数,但这不是C++14的一部分,而是概念lite的一部分。根据Herb Sutter的上一次行程报告,概念lite可能会成为C++1z的一部分。

我相信gcc允许将其作为扩展,如果我们使用-pedantic编译您的程序,gcc将警告:

 warning: ISO C++ forbids use of 'auto' in parameter declaration [-Wpedantic]
 auto func(auto x)
           ^

因此,从概念lite提案中,我们可以看到:

auto func(auto x)
{
    std::cout << x << std::endl;
    return x.getx();
}

相当于:

template <typename T1>
auto func(T1 x)
{
    std::cout << x << std::endl;
    return x.getx();
}

因此CCD_ 2将被推导为int。编译器会正确地给你一个错误,就像下面来自gcc的错误一样(请查看实时):

error: request for member 'getx' in 'x', which is of non-class type 'int'
     return x.getx();
                   ^

提案章节5.1.1[dcl.fct]:对此进行了说明

在参数声明子句中使用auto或概念名称应解释为使用具有相同约束和命名概念。[注:实现这一点尚未明确--尾注][示例:泛型下声明的函数

auto f(auto x, const Regular& y);

相当于以下声明

template<typename T1, Regular T2>
  auto f(T1 x, const T2&);

--结束示例]

auto作为参数类型的规则与模板参数的规则相同。

auto func(auto x)相当于template<typename T> auto func(T x)

不过,我不是引用具体规则标准的律师。