-
-
[分享]《探索现代化C++》泛读笔记摘要11
-
发表于: 2022-9-17 18:47 4611
-
《探索现代化C++》泛读笔记摘要11
Chapter 3 通用编程
Lambda
C++11 的产物
1 | [] (double x) { return sin(x) + cos(x);} |
值捕获
1 2 | double phi = 2.5 ; auto sin_phi = [phi](double x){ return sin(phi * x); }; |
引用捕获
1 2 | double phi = 2.5 ,xi = 0.2 ; auto pxr = [&phi,&xi] (double x) { return sin(phi * x) + cos(x) * xi;}; |
常见捕获方式
1 2 3 4 | [ = ] 全部值捕获 [&] 全部引用捕获 [ = ,&a,&b,&c] a,b,c采用引用捕获,其他值捕获 [&,a,b,c] a,b,c采用值捕获,其他引用捕获 |
C++14 初始化捕获
能为现有变量引入新的名称以及创建新的变量。
1 2 | int x = 4 ; auto l = [&r = x,i = x + 1 ]() {r + = 2 ; return i + 1 ;}; |
变量模板
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | template<size_t N> auto derive = [] (auto f,auto x,auto h){ auto prev = [&](auto x2) { return derive<N - 1 >(f,x2,h); }; return (prev(x + h) - prev(x)) / h; }; template<> auto derive< 0 > = [] (auto f,auto x,auto h){ return f(x); }; auto f = [](double x) { return 2.0 * std::cos(x) + x * x;}; cout<< "f''(1)=" << derive< 2 >(f, 1.0 , 1e - 3 )<<endl; cout<< "f(5) (1)=" << derive< 5 >(f, 1.0 , 1e - 3 )<<endl; |
C++17 编译时if
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | template <size_t N> auto derive = [] (auto f, auto h) { if constexpr (N = = 0 ) { return [f] (auto x) { return f(x); }; } else { auto prev = derive<N - 1 >(f, h); return [ = ](auto x){ return (prev(x + h) - prev(x)) / h;}; } }; auto f = [] (double x) { return 2.0 * std::cos(x) + x * x; }; auto d2f = derive< 2 >(f, 1e - 3 ); auto d5f = derive< 5 >(f, 1e - 3 ); cout ≪ "f''(1) = " ≪ d2f( 1.0 ) ≪ endl; cout ≪ "f(5)(1) = " ≪ d5f( 1.0 ) ≪ endl; |
C++20 Concepts
Concepts定义一个集合,用于限定模板参数的类型。
定义一个Concepts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | template <typename Iter , typename Value> Value accumulate( Iter first, Iter last, Value init) requires Summable< Iter , Value> { for (; first ! = last; + + first) init + = * first; return init; } template <typename Iter , typename Value> requires Summable< Iter , Value> Value accumulate( Iter first, Iter last, Value init); template <typename Iter , typename Value> concept Summable = requires ( Iter it, Value init) { requires std::input_iterator< Iter >; requires std::is_copy_constructible_v<Value>; Value{ init }; / / Attempt a copy init + = * it; }; |
不可拷贝构造的类
1 2 3 4 5 6 7 8 9 10 11 12 13 | struct uncopyable { uncopyable( int v) : v{v} {} uncopyable(const uncopyable&) = delete; uncopyable(uncopyable&&) = default; uncopyable& operator + = (const uncopyable& rhs) & { v + = rhs.v; return * this; } operator int () const { return v; } int v; }; |
不可移动构造的类:
1 2 3 4 5 6 | struct unmovable { unmovable(const unmovable&) = default; unmovable(unmovable&&) = delete; / / ... remainder like uncopyable }; |
赞赏
他的文章
- 定位Windows分页结构内存区域 6915
- [原创]2022年,工业级EDR绕过蓝图 28273
- [分享]《探索现代化C++》泛读笔记摘要20 完! 7310
- [分享]《探索现代化C++》泛读笔记摘要19 7562
- [原创]摘微过滤驱动回调的研究-续 10163
看原图
赞赏
雪币:
留言: