Search code examples
c++templatesc++14auto

How do auto arguments work internally?


Consider the code,

#include <cstdio>

auto f(const auto &loc){
  printf("Location: %p\n", &loc);
}

int main()
{
  auto x {1};
  auto y {2.3};
  f(x);
  f(y);
}

compile with g++ -std=c++14 dummy.cpp

Question:

For template functions, the type is explicitly mentioned(f<int>(2)) at compile time.

How does the function f accept arguments of different type?


Solution

  • Under the Concept Technical Specification the 'function'

    auto f(const auto &loc){
      printf("Location: %p\n", &loc);
    }
    

    is in fact a template (abbreviated function template declaration) and is equivalent to (but shorter and easier to read than)

    template<typename T>
    void f(const T&loc){
      printf("Location: %p\n", &loc);
    }
    

    Note, however, that the form using auto is not as of yet part of any C++ standard, but only of the Concept Technical Specification for concepts and constraints, which looks very powerful (but AFAIK is only supported by GNU's gcc version ≥6.1 with option -fconcepts).