5.4 现代C++示例
cpp
复制代码
#include <iostream>
#include <vector>
#include <algorithm>
#include <ranges>
#include <memory>

// 使用模板和概念约束泛型函数
template<typename T>
concept Numeric = std::is_arithmetic_v<T>;

template<Numeric T>
class Matrix {
    std::vector<T> data;
    size_t rows_, cols_;
    
public:
    Matrix(size_t r, size_t c) : data(r * c), rows_(r), cols_(c) {}
    
    T& operator()(size_t i, size_t j) { return data[i * cols_ + j]; }
    size_t rows() const { return rows_; }
    size_t cols() const { return cols_; }
    
    // 使用范围库进行惰性求值
    auto row(size_t i) { 
        return std::views::drop(data, i * cols_) 
             | std::views::take(cols_); 
    }
};

int main() {
    Matrix<double> m(3, 3);
    
    // 使用智能指针自动管理内存
    auto result = std::make_unique<Matrix<double>>(3, 1);
    
    // 使用并行算法
    std::vector<int> v = {3, 1, 4, 1, 5, 9, 2, 6, 5};
    std::sort(std::execution::par, v.begin(), v.end());
    
    // 使用范围管道
    auto even_squares = v 
        | std::views::filter([](int x) { return x % 2 == 0; })
        | std::views::transform([](int x) { return x * x; });
    
    for (int x : even_squares) {
        std::cout << x << " ";
    }
    std::cout << std::endl;
}