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实现的。有空时可以继续关注,函数式编程。

原文链接: https://www.cnblogs.com/thomas76/p/8674679.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    C++ generic lambda

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/397518

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年4月11日 上午9:13
下一篇 2023年4月11日 上午9:13

相关推荐