C++ 14标准对auto作为参数类型的说法是什么

Mam*_*mma 5 c++ auto c++14

让我们看看下面的代码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

编译器如何确定(20)是int还是Test对象?Test的构造函数不明确,那么标准对它有什么看法呢?

Sha*_*our 6

所以,虽然GCC允许汽车在功能参数这不是C++ 14的一部分,但一部分概念,精简版,其可能成为C++ 1Z部分根据香草萨特的最后一趟报告.

我相信gcc允许这个作为扩展,如果我们使用-pedanticgcc 编译你的程序将警告:

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

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

auto func(auto x)
{
    std::cout << x << std::endl;
    return x.getx();
}
Run Code Online (Sandbox Code Playgroud)

相当于:

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

因此x将推断为int.编译器将正确地给你一个错误,如gcc中的以下错误(请参见实时):

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

这在提案部分5.1.1 [dcl.fct]中介绍:

在parameter-declaration-clause中使用auto或concept-name应解释为使用具有相同约束和命名概念的类型参数.[注意:实现这一目标的确切机制尚未明确.-end note] [示例:下面声明的泛型函数

auto f(auto x, const Regular& y);
Run Code Online (Sandbox Code Playgroud)

相当于以下声明

template<typename T1, Regular T2>
  auto f(T1 x, const T2&);
Run Code Online (Sandbox Code Playgroud)

- 末端的例子]