C++14부터 lambda에 auto 타입을 사용할 수 있게 되어 이것을 "polymorphic lambda" (다형성을 가진 람다)라고 부르며, 일종의 "function template" (함수 템플릿)이라고 볼 수 있다.
아래 예제에서 identity라는 람다 함수는 파라미터로 받은 값을 그대로 반환하는 함수이다. 그런데 파라미터가 어떤 타입이더라도 받고 싶은데, 이런 경우에 템플릿을 이용하면 아주 편리하다. C++14에서는 람다 함수의 파라미터로 auto 타입을 사용할 수 있게 되어 다음과 같이 사용할 수 있게 되었다.
#include <iostream>
using namespace std;
int main(void)
{
auto identity = [](auto a) { return a; };
int three = identity(3);
char const* hello = identity("hello");
cout << three << endl;
cout << hello << endl;
return 0;
}
3
hello
앞서 정의한 identity 함수는 타입이 없었지만, 다시 함수 포인터로 만들면서 타입을 지정할 수 있다. fpi나 fpc 등의 함수 포인터는 타입을 가진다.
#include <iostream>
using namespace std;
int main(void)
{
int (*fpi)(int) = identity;
char (*fpc)(char) = identity;
string (*fps)(string) = identity;
cout << fpi(4) << endl;
cout << fpc('w') << endl;
cout << fps("world") << endl;
return 0;
}
4
w
world