0

I was playing with C++14 and lambda functions today and tried to write the following code:

#include <iostream>

auto getAddFunction() {
  return [](auto x, auto y) {
    return x+y;
  };
}

int main()
{
  auto func = getAddFunction();

  int x = 3, y = 4;
  int z = func(x, y);
  std::cout << z << std::endl;

  double a = 3.5, b = 4.7;
  double c = func(a, b);
  std::cout << c << std::endl;

  std::complex<double> e {1, 2};
  std::complex<double> f {3, 4};
  std::complex<double> g = func(e, f);
  std::cout << g << std::endl;

  return 0;
}

I tried to compile the code and I got the result below, which is the correct result:

7
8.2
(4,6)

I wouldn't have had difficulty understanding how the compiler was able to produce the correct result if the function getAddFunction was defined using templates. However, it is defined using auto and as far as my understanding goes, the compiler will try to guess the type, rather than generate multiple bodies for the function like in templates. But what seems to happen here is exactly what would have happened with templates, i.e. the compiler is generated multiple function bodies for each different data type, even though I am using the same exact lambda function variable!

Any one has an explanation why this is happening?

Rafid
  • 18,991
  • 23
  • 72
  • 108
  • 1) Lambdas are distinct. 2) `auto` follows template argument deduction rules. –  Dec 13 '14 at 23:37
  • Maybe its just using `double` all the way. Since what the compiler knows about your `auto` variables is that they will do arithmetic, it may be simply using the type that works for all arithmetic cases. – Havenard Dec 13 '14 at 23:41
  • @Havenard, I considered that possibility too, and this is the reason why I also added std::complex at the end, which disproved this possibility. – Rafid Dec 13 '14 at 23:41
  • 3
    @Havenard Totally false. Read the answer linked as the duplicate. – Barry Dec 13 '14 at 23:42

0 Answers0