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?