Search code examples
c++gccauto

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?


Solution

  • 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.