Last active
August 29, 2015 14:26
-
-
Save icedac/3c15d65d752d434afa74 to your computer and use it in GitHub Desktop.
generic lambda에 대한 고찰
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// lambda 고찰 #1 | |
// generic lambda의 타입은 어떻게 되는가? | |
void test1() | |
{ | |
auto f = [](auto x, auto y) // c++14: generic lambda | |
{ static int count = 0; printf("(%s) count:%d\n", __func__, count++); | |
return x + y; | |
}; | |
auto v = f(5, 1.5); // count:0 | |
auto s = f(std::string("ice"), "dac"); // count:0 : 서로 다른 lambda 함수가 호출되었다. (당연하지만) | |
auto v2 = f(10, 1.5); // count:1 | |
std::function< void(int, float) > fun1 = f; | |
std::function< void(std::string, const char*) > fun2 = f; // 서로 다른 std::function에 바인딩 잘됨 | |
// template 함수 처럼 처리 되는데 따로 type을 지정하지 않아도 compile-time에 서로 다른 람다함수가 매칭된다. | |
// return 하면 어떻게 되는가? 라는 의문이 든다. | |
} | |
// lambda 고찰 #2 | |
// generic lambda를 return 할 수 있는가?(first class 인가?) 당연히 있겠지? | |
auto test2_1() // c++14: return type deduction | |
{ | |
auto f = [](auto x, auto y) // c++14: generic lambda | |
{ | |
static int count = 0; | |
printf("(%s) count:%d\n", __func__, count++); | |
return x + y; | |
}; | |
return f; | |
} | |
template < typename F, typename X, typename Y > | |
auto test2_3(F f, const X& x, const Y& y ) | |
{ | |
return f(x, y); | |
} | |
void test2_2() | |
{ | |
printf("(%s)\n", __func__); | |
auto f = test2_1(); | |
auto v = f(5, 1.5); // count:0 | |
auto s = f(std::string("ice"), "dac"); // count:0 | |
auto v2 = f(10, 1.5); // count:1 | |
auto s2 = test2_3(f, std::string("fcuk"), "you"); | |
auto v3 = test2_3(f, 6, 2.5 ); | |
// std::function<>으로 매칭되지 않고도, template parameter나 | |
// auto return deduction 등으로 리턴과 param apss가 잘된다. | |
// 일반 lambda와 다른 generic lambda type으로 구현된 듯 보인다. | |
// parameter type 들의 튜플별 함수 테이블으로 추정. | |
} | |
// 은 나중에 찾았는데. | |
auto lambda = [](auto a, auto b) { return a * b; }; | |
// 위의 코드가 | |
struct lambda1 | |
{ | |
template<typename A, typename B> | |
auto operator()(A a, B b) const -> decltype(a * b) | |
{ | |
return a * b; | |
} | |
}; | |
auto lambda = lambda1(); | |
// 이 위의 c++ 코드와 근본적으로 같다. | |
// ref: http://cpprocks.com/an-overview-of-c14-language-features/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment