'auto' not allowed in function prototype with Clang

五迷三道 提交于 2019-11-29 09:14:06

As we see from the ISO C++ discussion mailing: decltype(auto) parameters vs. perfect forwarding auto parameters of non-lambdas is part of concepts lite and therefore not in C++14:

clang is correct in the sense that we don't yet have auto parameters. Concepts lite may bring those, but C++14 doesn't have them.

If we use the -pedantic flag with gcc we receive the following warning:

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

So this looks like an extension.

As dyp pointed out, polymorphic lambdas did make it into C++14 and do allow auto parameters, an example taken from the paper:

// '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");

Which is incidentally the same functionality you want to implement in your example.

Although your specific syntax did not make it to C++14, a similar option which did is:

static auto foo = [](auto bar) { return bar; };

which achieves basically the same thing.

You can use a template instead:

template<class A>
A foo(A bar) { return bar; }

Auto is only allowed when the Compiler can deduce the type from the context.

The compiler cannot infer the type from the context.

What's wrong with doing

template<typename Y>
Y foo(Y bar){return bar;}

and must you pass bar by value?

In your case you can use the trailing return type syntax:

auto foo(auto bar) -> decltype(bar)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!