C++ generic lambda

考虑如下代码:

 1 #include <iostream>
 2 struct callable_type  
 3 {  
 4     template<typename T, typename U>  
 5     auto operator()(T x, U y) const {return x + y;}  
 6 };  
 7 auto fake_lambda = callable_type{}; 
 8 int main(){
 9     auto ret = fake_lambda(1,2); //ret==3
10     std::cout << ret;
11 }

函数对象可以是模板化的operator(), lambda是否亦可以generic化呢?

1 #include <iostream>
2 using namespace std::string_literals;
3 int main(){
4     auto  lambda = [](auto x, auto y) { return x + y; };  
5     std::cout << lambda(1, 2) << std::endl;  
6     std::cout << lambda("hello"s, " world"s) << std::endl;
7 }

lambda返回一个lambda,实现函数式编程成为可能:

 1 #include <iostream>
 2 
 3 auto bind1st = [](auto F, int fst) {
 4     return [=]( auto&&... others ){
 5         return F(fst, others...);
 6     };
 7 };
 8 
 9 int add(int a,int b,int c){
10     return a+b+c;
11 }
12 
13 int main(){
14 
15     auto add1 = bind1st(foo,1);
16     auto ret = add1(2,3); //ret==6
17     std::cout << ret ;
18 }

这不就是个bind1st吗?使用lambda实现的。有空时可以继续关注,函数式编程。

posted @ 2018-03-30 10:13  thomas76  阅读(149)  评论(0编辑  收藏  举报