简体   繁体   中英

Declaring function parameter type as 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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM