将函数参数类型声明为 auto

qua*_*ell 3 c++ gcc auto

我正在使用 GCC 6.3,令我惊讶的是以下代码片段确实可以编译。

auto foo(auto x) { return 2.0 * x; }
...
foo(5);
Run Code Online (Sandbox Code Playgroud)

AFAIK 它是 GCC 扩展。与以下内容进行比较:

template <typename T, typename R>
R foo(T x) { return 2.0 * x; }
Run Code Online (Sandbox Code Playgroud)

除了返回类型推导之外,上面的声明是否等效?

Rei*_*ica 5

使用相同的 GCC (6.3) 和该-Wpedantic标志将生成以下警告:

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

在较新版本的 GCC 中编译此文件时,即使没有-Wpedantic,也会生成此警告,提醒您有关该-fconcepts标志的信息:

warning: use of 'auto' in parameter declaration only available with -fconcepts
  auto foo(auto x)
          ^~~~
Compiler returned: 0
Run Code Online (Sandbox Code Playgroud)

事实上,概念使得这样:

void foo(auto x)
{
    auto y = 2.0*x;
}
Run Code Online (Sandbox Code Playgroud)

相当于这个:

template<class T>
void foo(T x)
{
    auto y = 2.0*x;
}
Run Code Online (Sandbox Code Playgroud)

请参阅此处:“如果任何函数参数使用占位符(或者auto是受约束类型),则函数声明将改为缩写的函数模板声明:[...](概念 TS)”——强调我的。