【问题标题】:What does the C++14 standard say regarding auto as argument typeC++14 标准对 auto 作为参数类型有什么看法
【发布时间】:2015-11-09 10:22:36
【问题描述】:

让我们看看下面的代码:

#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 的构造函数不明确,那么标准对此有何规定?

【问题讨论】:

  • 1. auto 作为参数是概念 ts 的一部分。 2.x推导出为int,而不是Test
  • gcc accepts auto parameters even though it is part of concepts-lite 虽然如果你使用-pedantic gcc 会警告这不是iso C++。
  • 好的,谢谢,所以标准允许对 lambdas 使用 auto 但不允许对函数使用,对吗?
  • 是的,它允许用于通用 lambdas

标签: c++ c++14 auto


【解决方案1】:

因此,尽管 gcc 允许 auto 作为函数中的参数,但这不是 C++14 的一部分,而是 concepts-lite 的一部分,根据 Herb Sutter 的上次旅行报告,may become part of C++1z

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

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

所以从concept-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();
}

因此x 将被推断为int。编译器会理所当然地给你一个来自 gcc (see it live) 的错误:

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&);

——结束示例]

【讨论】:

  • 干杯伙伴,你和 Piotr Skotnicki 为我提供了很好的答案。
【解决方案2】:

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

auto func(auto x) 等价于template&lt;typename T&gt; auto func(T x)

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

【讨论】:

  • 您应该补充一点,这仅在 C++1z w/concepts lite 之后才成立。
猜你喜欢
  • 2021-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-24
  • 2019-12-17
  • 1970-01-01
相关资源
最近更新 更多