Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring function parameter type as auto

Tags:

c++

gcc

auto

I am using GCC 6.3 and to my surprise the following code fragment did compile.

auto foo(auto x) { return 2.0 * x; }
...
foo(5);

AFAIK it is GCC extension. Compare to the following:

template <typename T, typename R>
R foo(T x) { return 2.0 * x; }

Besides return type deduction are the above declaration equivalent?

like image 625
quantum_well Avatar asked Sep 20 '25 10:09

quantum_well


1 Answers

Using the same GCC (6.3) with the -Wpedantic flag will generate the following warning:

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

While compiling this in newer versions of GCC, even without -Wpedantic, will generate this warning, reminding you about the -fconcepts flag:

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

And indeed, concepts make this:

void foo(auto x)
{
    auto y = 2.0*x;
}

equivalent to this:

template<class T>
void foo(T x)
{
    auto y = 2.0*x;
}

See here: "If any of the function parameters uses a placeholder (either auto or a constrained type), the function declaration is instead an abbreviated function template declaration: [...] (concepts TS)" -- emphasis mine.

like image 55
Geezer Avatar answered Sep 23 '25 00:09

Geezer