使用Clang的函数原型中不允许'auto'

coi*_*oin 19 c++ auto clang++ c++14

使用Clang 3.5,3.6或3.7,带有std=c++1y以下代码的标志不能编译:

#include <iostream>
auto foo(auto bar) { return bar; }
int main() {
  std::cout << foo(5.0f) << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

给出的错误是:

错误:函数原型中不允许'auto'

我使用g ++ 4.9没有错误.是否因为Clang尚未实现此功能而产生此错误,还是因为我不被允许这样做而且GCC以某种方式允许它?

Sha*_*our 17

正如我们从ISO C++讨论邮件中看到的那样:decltype(auto)参数与非lambdas的完美转发自动参数是概念lite的一部分,因此不在C++ 14中:

clang是正确的,因为我们还没有自动参数.Concepts lite可能带来那些,但C++ 14没有它们.

如果我们使用-pedantic标志,gcc我们会收到以下警告:

warning: ISO C++ forbids use of 'auto' in parameter declaration [-Wpedantic]
  auto foo(auto bar) { return bar; }
           ^
Run Code Online (Sandbox Code Playgroud)

所以这看起来像是一个扩展.

正如dyp所指出的那样,多态lambda确实将它变成了C++ 14并且允许自动参数,这是一篇来自论文的例子:

// 'Identity' is a lambda that accepts an argument of any type and
// returns the value of its parameter.
auto Identity = [](auto a) { return a; };
int three = Identity(3);
char const* hello = Identity("hello");
Run Code Online (Sandbox Code Playgroud)

顺便提一下,您希望在示例中实现相同的功能.


M.M*_*M.M 10

虽然您的特定语法没有达到C++ 14,但类似的选项是:

static auto foo = [](auto bar) { return bar; };
Run Code Online (Sandbox Code Playgroud)

这实现了基本相同的事情.


Tho*_*ber 7

您可以使用模板代替:

template<class A>
A foo(A bar) { return bar; }
Run Code Online (Sandbox Code Playgroud)

仅当编译器可以从上下文推断类型时才允许使用 Auto。