核心主题:C++进阶与未来发展方向
今日学习目标:
- 深入理解C++20/23/26的新特性。
- 掌握协程(Coroutines)的原理和使用。
- 学习模块化编程(Modules)。
- 了解元编程和编译期计算的进阶技巧。
- 掌握概念(Concepts)的高级用法。
- 学习范围(Ranges)和视图(Views)。
- 探索C++在AI、游戏、嵌入式等领域的应用。
第一部分:现代C++新特性深入
1. C++20 协程(Coroutines)
协程基础概念:
#include <iostream>
#include <coroutine>
#include <future>
#include <thread>
// 简单的协程框架
template<typename T>
struct Generator {
struct promise_type {
T value_;
Generator get_return_object() {
return Generator{std::coroutine_handle<promise_type>::from_promise(*this)};
}
std::suspend_always initial_suspend() { return {}; }
std::suspend_always final_suspend() noexcept { return {}; }
void unhandled_exception() { std::terminate(); }
std::suspend_always yield_value(T value) {
value_ = value;
return {};
}
void return_void() {}
};
std::coroutine_handle<promise_type> handle_;
explicit Generator(std::coroutine_handle<promise_type> handle) : handle_(handle) {}
~Generator() { if (handle_) handle_.destroy(); }
// 禁止拷贝
Generator(const Generator&) = delete;
Generator& operator=(const Generator&) = delete;
// 允许移动
Generator(Generator&& other) noexcept : handle_(other.handle_) {
other.handle_ = nullptr;
}
Generator& operator=(Generator&& other) noexcept {
if (this != &other) {
if (handle_) handle_.destroy();
handle_ = other.handle_;
other.handle_ = nullptr;
}
return *this;
}
T value() const { return handle_.promise().value_; }
bool next() {
if (!handle_ || handle_.done()) return false;
handle_.resume();
return !handle_.done();
}
};
// 生成器协程示例
Generator<int> range(int start, int end, int step = 1) {
for (int i = start; i < end; i += step) {
co_yield i;
}
}
// 异步任务协程
template<typename T>
struct AsyncTask {
struct promise_type {
T value_;
std::exception_ptr exception_;
AsyncTask get_return_object() {
return AsyncTask{std::coroutine_handle<promise_type>::from_promise(*this)};
}
std::suspend_never initial_suspend() { return {}; }
std::suspend_always final_suspend() noexcept { return {}; }
void unhandled_exception() { exception_ = std::current_exception(); }
template<typename U>
void return_value(U&& value) {
value_ = std::forward<U>(value);
}
};
std::coroutine_handle<promise_type> handle_;
explicit AsyncTask(std::coroutine_handle<promise_type> handle) : handle_(handle) {}
~AsyncTask() { if (handle_) handle_.destroy(); }
T get() {
if (!handle_.done()) {
handle_.resume();
}
if (handle_.promise().exception_) {
std::rethrow_exception(handle_.promise().exception_);
}
return handle_.promise().value_;
}
};
AsyncTask<int> async_computation() {
std::cout << "开始异步计算..." << std::endl;
co_await std::suspend_always{};
// 模拟耗时操作
std::this_thread::sleep_for(std::chrono::milliseconds(100));
std::cout << "计算完成" << std::endl;
co_return 42;
}
void demonstrate_coroutines() {
std::cout << "=== C++20 协程演示 ===" << std::endl;
// 生成器协程
std::cout << "生成器协程:" << std::endl;
auto gen = range(1, 10, 2);
while (gen.next()) {
std::cout << gen.value() << " ";
}
std::cout << std::endl;
// 异步任务协程
std::cout << "异步任务协程:" << std::endl;
auto task = async_computation();
std::cout << "异步任务创建,等待结果..." << std::endl;
int result = task.get();
std::cout << "结果: " << result << std::endl;
}
// 更复杂的协程:网络IO模拟
Generator<std::string> async_data_stream() {
const char* data[] = {"数据块1", "数据块2", "数据块3", "数据块4"};
for (int i = 0; i < 4; ++i) {
std::cout << "产生数据: " << data[i] << std::endl;
co_yield data[i];
// 模拟网络延迟
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
}
void demonstrate_async_stream() {
std::cout << "\n=== 异步数据流 ===" << std::endl;
auto stream = async_data_stream();
while (stream.next()) {
std::cout << "接收到: " << stream.value() << std::endl;
}
}2. C++20 模块(Modules)
数学模块(math.ixx):
// math.ixx - C++20模块
export module math;
export namespace math {
constexpr double PI = 3.14159265358979323846;
export double sqrt(double x) {
if (x < 0) throw std::invalid_argument("负数不能开平方");
double guess = x;
for (int i = 0; i < 10; ++i) {
guess = (guess + x / guess) / 2.0;
}
return guess;
}
export double sin(double x) {
// 简化的sin实现(实际应该用泰勒展开)
x = std::fmod(x, 2 * PI);
return std::sin(x);
}
export double cos(double x) {
x = std::fmod(x, 2 * PI);
return std::cos(x);
}
export template<typename T>
T clamp(T value, T min, T max) {
if (value < min) return min;
if (value > max) return max;
return value;
}
export class Vector2 {
public:
double x, y;
Vector2(double x = 0, double y = 0) : x(x), y(y) {}
Vector2 operator+(const Vector2& other) const {
return Vector2(x + other.x, y + other.y);
}
Vector2 operator-(const Vector2& other) const {
return Vector2(x - other.x, y - other.y);
}
Vector2 operator*(double scalar) const {
return Vector2(x * scalar, y * scalar);
}
double magnitude() const {
return sqrt(x * x + y * y);
}
Vector2 normalized() const {
double mag = magnitude();
if (mag == 0) return Vector2(0, 0);
return Vector2(x / mag, y / mag);
}
double dot(const Vector2& other) const {
return x * other.x + y * other.y;
}
};
} // namespace math工具模块(utils.ixx):
// utils.ixx
export module utils;
import <string>;
import <vector>;
import <algorithm>;
export namespace utils {
export template<typename Container, typename Predicate>
bool all_of(const Container& container, Predicate pred) {
return std::all_of(container.begin(), container.end(), pred);
}
export template<typename Container, typename T>
bool contains(const Container& container, const T& value) {
return std::find(container.begin(), container.end(), value) != container.end();
}
export std::string to_upper(std::string str) {
std::transform(str.begin(), str.end(), str.begin(), ::toupper);
return str;
}
export std::string to_lower(std::string str) {
std::transform(str.begin(), str.end(), str.begin(), ::tolower);
return str;
}
export template<typename T>
class Singleton {
protected:
Singleton() = default;
public:
static T& instance() {
static T instance;
return instance;
}
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
};
} // namespace utils主程序使用模块:
// main.cpp - 使用模块
import math;
import utils;
import <iostream>;
import <vector>;
void demonstrate_modules() {
std::cout << "=== C++20 模块演示 ===" << std::endl;
// 使用数学模块
math::Vector2 v1(3, 4);
math::Vector2 v2(1, 2);
auto v3 = v1 + v2;
std::cout << "向量相加: (" << v3.x << ", " << v3.y << ")" << std::endl;
std::cout << "向量长度: " << v1.magnitude() << std::endl;
// 使用工具模块
std::vector<int> numbers = {1, 2, 3, 4, 5};
bool all_positive = utils::all_of(numbers, [](int n) { return n > 0; });
std::cout << "所有数字都是正数: " << std::boolalpha << all_positive << std::endl;
std::string text = "Hello Modules";
std::cout << "大写: " << utils::to_upper(text) << std::endl;
std::cout << "小写: " << utils::to_lower(text) << std::endl;
// 使用数学常量
std::cout << "PI: " << math::PI << std::endl;
std::cout << "平方根: " << math::sqrt(25.0) << std::endl;
}
// 配置管理器使用单例模式
class ConfigManager : public utils::Singleton<ConfigManager> {
friend class utils::Singleton<ConfigManager>;
private:
std::string config_path_;
ConfigManager() : config_path_("default.config") {}
public:
void set_config_path(const std::string& path) { config_path_ = path; }
std::string get_config_path() const { return config_path_; }
};
void demonstrate_singleton() {
auto& config = ConfigManager::instance();
std::cout << "配置路径: " << config.get_config_path() << std::endl;
config.set_config_path("new_config.xml");
std::cout << "新配置路径: " << config.get_config_path() << std::endl;
}3. C++20 范围(Ranges)和视图(Views)
#include <iostream>
#include <vector>
#include <ranges>
#include <algorithm>
#include <numeric>
void demonstrate_ranges() {
std::cout << "=== C++20 范围库演示 ===" << std::endl;
std::vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// 传统方式 vs 范围方式
std::cout << "传统方式过滤和转换:" << std::endl;
std::vector<int> result;
for (int n : numbers) {
if (n % 2 == 0) {
result.push_back(n * n);
}
}
for (int n : result) std::cout << n << " ";
std::cout << std::endl;
std::cout << "范围方式过滤和转换:" << std::endl;
auto even_squares = numbers
| std::views::filter([](int n) { return n % 2 == 0; })
| std::views::transform([](int n) { return n * n; });
for (int n : even_squares) std::cout << n << " ";
std::cout << std::endl;
// 更多范围操作
std::cout << "\n更多范围操作:" << std::endl;
// 取前5个元素
auto first_five = numbers | std::views::take(5);
std::cout << "前5个元素: ";
for (int n : first_five) std::cout << n << " ";
std::cout << std::endl;
// 反转
auto reversed = numbers | std::views::reverse;
std::cout << "反转: ";
for (int n : reversed) std::cout << n << " ";
std::cout << std::endl;
// 过滤和转换组合
auto complex_view = numbers
| std::views::filter([](int n) { return n > 5; })
| std::views::transform([](int n) { return n * 2; })
| std::views::take(3);
std::cout << "复杂视图: ";
for (int n : complex_view) std::cout << n << " ";
std::cout << std::endl;
// 范围算法
std::cout << "\n范围算法:" << std::endl;
// 排序
std::vector<int> unsorted = {5, 2, 8, 1, 9};
std::ranges::sort(unsorted);
std::cout << "排序后: ";
for (int n : unsorted) std::cout << n << " ";
std::cout << std::endl;
// 查找
auto it = std::ranges::find(numbers, 7);
if (it != numbers.end()) {
std::cout << "找到7在位置: " << std::distance(numbers.begin(), it) << std::endl;
}
// 计数
int count = std::ranges::count_if(numbers, [](int n) { return n % 2 == 0; });
std::cout << "偶数个数: " << count << std::endl;
}
// 自定义范围适配器
template<std::ranges::input_range R>
auto chunk_view(R&& range, std::size_t chunk_size) {
return range | std::views::transform([chunk_size, index = 0](auto&& item) mutable {
return std::pair{index++ / chunk_size, std::forward<decltype(item)>(item)};
}) | std::views::chunk_by([](auto&& a, auto&& b) {
return a.first == b.first;
}) | std::views::transform([](auto&& chunk) {
return chunk | std::views::values;
});
}
void demonstrate_custom_range() {
std::cout << "\n=== 自定义范围适配器 ===" << std::endl;
std::vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// 使用自定义的分块视图
auto chunks = chunk_view(numbers, 3);
int chunk_num = 0;
for (auto chunk : chunks) {
std::cout << "块 " << ++chunk_num << ": ";
for (int n : chunk) {
std::cout << n << " ";
}
std::cout << std::endl;
}
}第二部分:高级元编程
1. 概念(Concepts)高级用法
#include <iostream>
#include <concepts>
#include <vector>
#include <list>
#include <type_traits>
// 基础概念定义
template<typename T>
concept Arithmetic = std::is_arithmetic_v<T>;
template<typename T>
concept Container = requires(T container) {
typename T::value_type;
typename T::iterator;
typename T::const_iterator;
{ container.begin() } -> std::same_as<typename T::iterator>;
{ container.end() } -> std::same_as<typename T::iterator>;
{ container.size() } -> std::integral;
};
template<typename T>
concept Sortable = Container<T> &&
requires(T container) {
std::sort(container.begin(), container.end());
};
template<typename T>
concept Hashable = requires(T a) {
{ std::hash<T>{}(a) } -> std::convertible_to<std::size_t>;
};
// 高级概念:可序列化
template<typename T>
concept Serializable = requires(T obj, std::ostream& os) {
{ obj.serialize(os) } -> std::same_as<void>;
};
template<typename T>
concept Deserializable = requires(T obj, std::istream& is) {
{ T::deserialize(is) } -> std::same_as<T>;
};
// 组合概念
template<typename T>
concept SerializableContainer = Container<T> && Serializable<typename T::value_type>;
// 要求概念
template<typename T>
requires Arithmetic<T>
class MathVector {
private:
std::vector<T> data_;
public:
MathVector() = default;
template<Container C>
requires std::same_as<typename C::value_type, T>
MathVector(const C& container) : data_(container.begin(), container.end()) {}
T dot(const MathVector& other) const requires requires(T a, T b) { a * b; } {
if (data_.size() != other.data_.size()) {
throw std::invalid_argument("向量维度不匹配");
}
T result = 0;
for (size_t i = 0; i < data_.size(); ++i) {
result += data_[i] * other.data_[i];
}
return result;
}
MathVector operator+(const MathVector& other) const {
MathVector result;
result.data_.resize(data_.size());
for (size_t i = 0; i < data_.size(); ++i) {
result.data_[i] = data_[i] + other.data_[i];
}
return result;
}
};
// 概念特化
template<typename T>
struct Serializer {
static void serialize(const T& obj, std::ostream& os) {
os << obj;
}
static T deserialize(std::istream& is) {
T obj;
is >> obj;
return obj;
}
};
// 可序列化类型的特化
template<Serializable T>
struct Serializer<T> {
static void serialize(const T& obj, std::ostream& os) {
obj.serialize(os);
}
};
// SFINAE风格的旧代码 vs 概念风格的新代码
namespace old_style {
template<typename T>
std::enable_if_t<std::is_arithmetic_v<T>, T>
square(T x) {
return x * x;
}
}
namespace new_style {
template<Arithmetic T>
T square(T x) {
return x * x;
}
}
// 高级概念:函数对象
template<typename F, typename... Args>
concept Invocable = std::is_invocable_v<F, Args...>;
template<typename F, typename R, typename... Args>
concept InvocableTo = std::is_invocable_r_v<R, F, Args...>;
void demonstrate_concepts() {
std::cout << "=== 高级概念演示 ===" << std::endl;
// 使用概念约束的函数
MathVector<double> vec1(std::vector{1.0, 2.0, 3.0});
MathVector<double> vec2(std::list{4.0, 5.0, 6.0});
auto vec3 = vec1 + vec2;
double dot_product = vec1.dot(vec2);
std::cout << "点积: " << dot_product << std::endl;
// 新旧风格对比
std::cout << "旧风格平方: " << old_style::square(5) << std::endl;
std::cout << "新风格平方: " << new_style::square(5.0) << std::endl;
// 概念检查
static_assert(Arithmetic<int>, "int应该是算术类型");
static_assert(Container<std::vector<int>>, "vector应该是容器");
static_assert(!Arithmetic<std::string>, "string不应该是算术类型");
std::cout << "所有概念检查通过!" << std::endl;
}2. 编译期计算进阶
#include <iostream>
#include <type_traits>
#include <array>
// 编译期字符串
template<typename CharT, CharT... Chars>
struct ConstString {
static constexpr CharT value[sizeof...(Chars) + 1] = {Chars..., '\0'};
static constexpr std::size_t size = sizeof...(Chars);
constexpr ConstString() = default;
template<std::size_t N>
constexpr ConstString(const CharT(&str)[N]) {
static_assert(N <= sizeof...(Chars) + 1, "字符串太长");
}
constexpr const CharT* c_str() const { return value; }
constexpr std::size_t length() const { return size; }
};
template<typename CharT, CharT... Chars>
constexpr CharT ConstString<CharT, Chars...>::value[sizeof...(Chars) + 1];
// 编译期字符串字面量
template<typename CharT, ConstString<CharT> Str>
constexpr auto operator""_cs() {
return Str;
}
// 编译期向量
template<typename T, std::size_t N>
class ConstexprVector {
private:
std::array<T, N> data_{};
std::size_t size_ = 0;
public:
constexpr ConstexprVector() = default;
constexpr void push_back(T value) {
if (size_ >= N) {
throw std::out_of_range("向量已满");
}
data_[size_++] = value;
}
constexpr T operator[](std::size_t index) const {
if (index >= size_) {
throw std::out_of_range("索引越界");
}
return data_[index];
}
constexpr std::size_t size() const { return size_; }
constexpr bool empty() const { return size_ == 0; }
constexpr auto begin() const { return data_.begin(); }
constexpr auto end() const { return data_.begin() + size_; }
};
// 编译期排序
template<typename T, std::size_t N>
constexpr std::array<T, N> constexpr_sort(std::array<T, N> arr) {
for (std::size_t i = 0; i < N - 1; ++i) {
for (std::size_t j = 0; j < N - i - 1; ++j) {
if (arr[j] > arr[j + 1]) {
std::swap(arr[j], arr[j + 1]);
}
}
}
return arr;
}
// 编译期斐波那契
template<std::size_t N>
struct Fibonacci {
static constexpr unsigned long long value =
Fibonacci<N - 1>::value + Fibonacci<N - 2>::value;
};
template<>
struct Fibonacci<0> {
static constexpr unsigned long long value = 0;
};
template<>
struct Fibonacci<1> {
static constexpr unsigned long long value = 1;
};
// 编译期素数检测
constexpr bool is_prime_impl(int n, int divisor) {
if (divisor * divisor > n) return true;
if (n % divisor == 0) return false;
return is_prime_impl(n, divisor + 2);
}
constexpr bool is_prime(int n) {
if (n <= 1) return false;
if (n == 2) return true;
if (n % 2 == 0) return false;
return is_prime_impl(n, 3);
}
// 编译期类型列表
template<typename... Ts>
struct TypeList {};
template<typename List>
struct ListSize;
template<typename... Ts>
struct ListSize<TypeList<Ts...>> {
static constexpr std::size_t value = sizeof...(Ts);
};
template<typename List, typename T>
struct ListContains;
template<typename T, typename... Ts>
struct ListContains<TypeList<Ts...>, T> {
static constexpr bool value = (std::is_same_v<T, Ts> || ...);
};
void demonstrate_compile_time() {
std::cout << "=== 编译期计算进阶 ===" << std::endl;
// 编译期斐波那契
std::cout << "编译期斐波那契数列:" << std::endl;
std::cout << "F(10) = " << Fibonacci<10>::value << std::endl;
std::cout << "F(20) = " << Fibonacci<20>::value << std::endl;
std::cout << "F(30) = " << Fibonacci<30>::value << std::endl;
// 编译期素数检测
std::cout << "\n编译期素数检测:" << std::endl;
std::cout << "17 是素数: " << is_prime(17) << std::endl;
std::cout << "25 是素数: " << is_prime(25) << std::endl;
// 编译期排序
constexpr std::array<int, 5> unsorted = {5, 2, 8, 1, 9};
constexpr auto sorted = constexpr_sort(unsorted);
std::cout << "\n编译期排序:" << std::endl;
std::cout << "排序前: ";
for (int n : unsorted) std::cout << n << " ";
std::cout << "\n排序后: ";
for (int n : sorted) std::cout << n << " ";
std::cout << std::endl;
// 编译期向量
constexpr auto create_vector = []() {
ConstexprVector<int, 10> vec;
vec.push_back(1);
vec.push_back(2);
vec.push_back(3);
return vec;
};
constexpr auto vec = create_vector();
std::cout << "\n编译期向量大小: " << vec.size() << std::endl;
// 类型列表
using MyTypes = TypeList<int, double, std::string, char>;
std::cout << "类型列表大小: " << ListSize<MyTypes>::value << std::endl;
std::cout << "包含double: " << ListContains<MyTypes, double>::value << std::endl;
std::cout << "包含float: " << ListContains<MyTypes, float>::value << std::endl;
}第三部分:C++在不同领域的应用
1. 游戏开发:简单的2D游戏引擎框架
#include <memory>
#include <vector>
#include <algorithm>
#include <cmath>
namespace game_engine {
// 基础数学类型
struct Vector2 {
float x, y;
Vector2(float x = 0, float y = 0) : x(x), y(y) {}
Vector2 operator+(const Vector2& other) const { return Vector2(x + other.x, y + other.y); }
Vector2 operator-(const Vector2& other) const { return Vector2(x - other.x, y - other.y); }
Vector2 operator*(float scalar) const { return Vector2(x * scalar, y * scalar); }
float length() const { return std::sqrt(x * x + y * y); }
Vector2 normalized() const {
float len = length();
return len > 0 ? Vector2(x / len, y / len) : Vector2(0, 0);
}
float dot(const Vector2& other) const { return x * other.x + y * other.y; }
};
// 组件系统
class Component {
public:
virtual ~Component() = default;
virtual void update(float delta_time) = 0;
virtual void render() = 0;
};
class TransformComponent : public Component {
public:
Vector2 position;
Vector2 scale{1, 1};
float rotation = 0;
void update(float delta_time) override {
// 位置更新逻辑
}
void render() override {
// 渲染逻辑
}
};
class SpriteComponent : public Component {
private:
std::string texture_path_;
Vector2 size_;
public:
SpriteComponent(const std::string& texture_path, const Vector2& size)
: texture_path_(texture_path), size_(size) {}
void update(float delta_time) override {
// 动画更新
}
void render() override {
// 渲染精灵
std::cout << "渲染精灵: " << texture_path_ << std::endl;
}
};
// 游戏对象
class GameObject {
private:
std::vector<std::unique_ptr<Component>> components_;
std::string tag_;
public:
GameObject(const std::string& tag = "") : tag_(tag) {}
template<typename T, typename... Args>
T* add_component(Args&&... args) {
auto component = std::make_unique<T>(std::forward<Args>(args)...);
T* ptr = component.get();
components_.push_back(std::move(component));
return ptr;
}
template<typename T>
T* get_component() {
for (auto& component : components_) {
if (auto ptr = dynamic_cast<T*>(component.get())) {
return ptr;
}
}
return nullptr;
}
void update(float delta_time) {
for (auto& component : components_) {
component->update(delta_time);
}
}
void render() {
for (auto& component : components_) {
component->render();
}
}
const std::string& get_tag() const { return tag_; }
};
// 场景管理
class Scene {
private:
std::vector<std::unique_ptr<GameObject>> objects_;
public:
GameObject* create_object(const std::string& tag = "") {
auto obj = std::make_unique<GameObject>(tag);
GameObject* ptr = obj.get();
objects_.push_back(std::move(obj));
return ptr;
}
void update(float delta_time) {
for (auto& obj : objects_) {
obj->update(delta_time);
}
}
void render() {
for (auto& obj : objects_) {
obj->render();
}
}
GameObject* find_with_tag(const std::string& tag) {
auto it = std::find_if(objects_.begin(), objects_.end(),
[&tag](const auto& obj) { return obj->get_tag() == tag; });
return it != objects_.end() ? it->get() : nullptr;
}
};
// 简单的物理系统
class PhysicsSystem {
public:
static bool check_collision(const Vector2& pos1, const Vector2& size1,
const Vector2& pos2, const Vector2& size2) {
return (pos1.x < pos2.x + size2.x && pos1.x + size1.x > pos2.x &&
pos1.y < pos2.y + size2.y && pos1.y + size1.y > pos2.y);
}
static Vector2 calculate_reflection(const Vector2& velocity, const Vector2& normal) {
float dot_product = velocity.dot(normal);
return velocity - normal * (2 * dot_product);
}
};
} // namespace game_engine
void demonstrate_game_engine() {
using namespace game_engine;
std::cout << "=== 简单游戏引擎演示 ===" << std::endl;
Scene scene;
// 创建玩家对象
auto* player = scene.create_object("Player");
auto* transform = player->add_component<TransformComponent>();
auto* sprite = player->add_component<SpriteComponent>("player.png", Vector2(32, 32));
transform->position = Vector2(100, 100);
// 创建敌人对象
auto* enemy = scene.create_object("Enemy");
enemy->add_component<TransformComponent>()->position = Vector2(200, 150);
enemy->add_component<SpriteComponent>("enemy.png", Vector2(32, 32));
// 更新和渲染
scene.update(0.016f); // 60 FPS
scene.render();
// 碰撞检测
Vector2 player_pos(100, 100);
Vector2 enemy_pos(200, 150);
Vector2 size(32, 32);
bool collision = PhysicsSystem::check_collision(player_pos, size, enemy_pos, size);
std::cout << "碰撞检测: " << std::boolalpha << collision << std::endl;
}2. AI和机器学习:简单的神经网络框架
#include <vector>
#include <random>
#include <algorithm>
#include <cmath>
namespace neural_network {
class Tensor {
private:
std::vector<std::vector<double>> data_;
std::size_t rows_, cols_;
public:
Tensor(std::size_t rows, std::size_t cols)
: rows_(rows), cols_(cols), data_(rows, std::vector<double>(cols, 0.0)) {}
Tensor(const std::vector<std::vector<double>>& data)
: data_(data), rows_(data.size()), cols_(data.empty() ? 0 : data[0].size()) {}
std::size_t rows() const { return rows_; }
std::size_t cols() const { return cols_; }
double& operator()(std::size_t i, std::size_t j) { return data_[i][j]; }
const double& operator()(std::size_t i, std::size_t j) const { return data_[i][j]; }
Tensor operator+(const Tensor& other) const {
Tensor result(rows_, cols_);
for (std::size_t i = 0; i < rows_; ++i) {
for (std::size_t j = 0; j < cols_; ++j) {
result(i, j) = data_[i][j] + other(i, j);
}
}
return result;
}
Tensor operator*(const Tensor& other) const {
// 简单的逐元素乘法
Tensor result(rows_, cols_);
for (std::size_t i = 0; i < rows_; ++i) {
for (std::size_t j = 0; j < cols_; ++j) {
result(i, j) = data_[i][j] * other(i, j);
}
}
return result;
}
Tensor dot(const Tensor& other) const {
if (cols_ != other.rows_) {
throw std::invalid_argument("矩阵维度不匹配");
}
Tensor result(rows_, other.cols_);
for (std::size_t i = 0; i < rows_; ++i) {
for (std::size_t j = 0; j < other.cols_; ++j) {
for (std::size_t k = 0; k < cols_; ++k) {
result(i, j) += data_[i][k] * other(k, j);
}
}
}
return result;
}
};
// 激活函数
class ActivationFunction {
public:
virtual ~ActivationFunction() = default;
virtual Tensor forward(const Tensor& input) = 0;
virtual Tensor backward(const Tensor& input) = 0;
};
class ReLU : public ActivationFunction {
public:
Tensor forward(const Tensor& input) override {
Tensor output(input.rows(), input.cols());
for (std::size_t i = 0; i < input.rows(); ++i) {
for (std::size_t j = 0; j < input.cols(); ++j) {
output(i, j) = std::max(0.0, input(i, j));
}
}
return output;
}
Tensor backward(const Tensor& input) override {
Tensor grad(input.rows(), input.cols());
for (std::size_t i = 0; i < input.rows(); ++i) {
for (std::size_t j = 0; j < input.cols(); ++j) {
grad(i, j) = input(i, j) > 0 ? 1.0 : 0.0;
}
}
return grad;
}
};
class Sigmoid : public ActivationFunction {
public:
Tensor forward(const Tensor& input) override {
Tensor output(input.rows(), input.cols());
for (std::size_t i = 0; i < input.rows(); ++i) {
for (std::size_t j = 0; j < input.cols(); ++j) {
output(i, j) = 1.0 / (1.0 + std::exp(-input(i, j)));
}
}
return output;
}
Tensor backward(const Tensor& input) override {
Tensor output = forward(input);
Tensor grad(input.rows(), input.cols());
for (std::size_t i = 0; i < input.rows(); ++i) {
for (std::size_t j = 0; j < input.cols(); ++j) {
grad(i, j) = output(i, j) * (1.0 - output(i, j));
}
}
return grad;
}
};
// 神经网络层
class Layer {
protected:
std::unique_ptr<ActivationFunction> activation_;
public:
virtual ~Layer() = default;
virtual Tensor forward(const Tensor& input) = 0;
virtual Tensor backward(const Tensor& grad_output) = 0;
virtual void update_weights(double learning_rate) = 0;
};
class DenseLayer : public Layer {
private:
Tensor weights_;
Tensor biases_;
Tensor input_;
Tensor output_;
public:
DenseLayer(std::size_t input_size, std::size_t output_size)
: weights_(output_size, input_size), biases_(output_size, 1) {
// Xavier初始化
std::random_device rd;
std::mt19937 gen(rd());
std::normal_distribution<double> dist(0.0, std::sqrt(2.0 / (input_size + output_size)));
for (std::size_t i = 0; i < output_size; ++i) {
for (std::size_t j = 0; j < input_size; ++j) {
weights_(i, j) = dist(gen);
}
biases_(i, 0) = 0.1;
}
activation_ = std::make_unique<ReLU>();
}
Tensor forward(const Tensor& input) override {
input_ = input;
Tensor z = weights_.dot(input_) + biases_;
output_ = activation_->forward(z);
return output_;
}
Tensor backward(const Tensor& grad_output) override {
Tensor activation_grad = activation_->backward(output_);
Tensor grad_input = grad_output * activation_grad;
// 计算权重和偏置的梯度
Tensor weight_grad = grad_input.dot(input_.transpose());
Tensor bias_grad = grad_input;
// 更新权重和偏置(在实际实现中需要存储梯度)
// 这里简化实现
// 计算传递给前一层的梯度
return weights_.transpose().dot(grad_input);
}
void update_weights(double learning_rate) override {
// 权重更新逻辑
// 简化实现
}
};
// 简单的神经网络
class NeuralNetwork {
private:
std::vector<std::unique_ptr<Layer>> layers_;
public:
void add_layer(std::unique_ptr<Layer> layer) {
layers_.push_back(std::move(layer));
}
Tensor forward(const Tensor& input) {
Tensor output = input;
for (auto& layer : layers_) {
output = layer->forward(output);
}
return output;
}
void backward(const Tensor& grad) {
Tensor grad_output = grad;
for (auto it = layers_.rbegin(); it != layers_.rend(); ++it) {
grad_output = (*it)->backward(grad_output);
}
}
void update(double learning_rate) {
for (auto& layer : layers_) {
layer->update_weights(learning_rate);
}
}
};
} // namespace neural_network
void demonstrate_neural_network() {
using namespace neural_network;
std::cout << "=== 简单神经网络演示 ===" << std::endl;
// 创建神经网络
NeuralNetwork network;
network.add_layer(std::make_unique<DenseLayer>(2, 4)); // 输入层到隐藏层
network.add_layer(std::make_unique<DenseLayer>(4, 1)); // 隐藏层到输出层
// 创建训练数据 (XOR问题)
Tensor inputs(4, 2);
Tensor targets(4, 1);
inputs(0, 0) = 0; inputs(0, 1) = 0; targets(0, 0) = 0;
inputs(1, 0) = 0; inputs(1, 1) = 1; targets(1, 0) = 1;
inputs(2, 0) = 1; inputs(2, 1) = 0; targets(2, 0) = 1;
inputs(3, 0) = 1; inputs(3, 1) = 1; targets(3, 0) = 0;
// 前向传播
Tensor output = network.forward(inputs);
std::cout << "神经网络输出:" << std::endl;
for (std::size_t i = 0; i < output.rows(); ++i) {
std::cout << "输入 [" << inputs(i, 0) << ", " << inputs(i, 1)
<< "] -> 输出: " << output(i, 0) << std::endl;
}
}第四部分:性能优化进阶
1. 内存池和对象池
#include <memory>
#include <vector>
#include <stack>
template<typename T, std::size_t BlockSize = 4096>
class MemoryPool {
private:
struct Block {
alignas(alignof(T)) char data[BlockSize];
Block* next = nullptr;
};
Block* head_ = nullptr;
std::stack<T*> free_list_;
public:
MemoryPool() = default;
~MemoryPool() {
while (head_) {
Block* next = head_->next;
::operator delete(head_);
head_ = next;
}
}
template<typename... Args>
T* construct(Args&&... args) {
T* obj = allocate();
new (obj) T(std::forward<Args>(args)...);
return obj;
}
void destroy(T* obj) {
if (obj) {
obj->~T();
deallocate(obj);
}
}
private:
T* allocate() {
if (free_list_.empty()) {
allocate_block();
}
T* obj = free_list_.top();
free_list_.pop();
return obj;
}
void deallocate(T* obj) {
free_list_.push(obj);
}
void allocate_block() {
Block* block = static_cast<Block*>(::operator new(sizeof(Block)));
block->next = head_;
head_ = block;
// 将块中的内存添加到空闲列表
constexpr std::size_t object_count = BlockSize / sizeof(T);
for (std::size_t i = 0; i < object_count; ++i) {
T* obj = reinterpret_cast<T*>(&block->data[i * sizeof(T)]);
free_list_.push(obj);
}
}
};
// 对象池
template<typename T>
class ObjectPool {
private:
std::vector<std::unique_ptr<T>> pool_;
std::size_t index_ = 0;
public:
template<typename... Args>
void preallocate(std::size_t count, Args&&... args) {
pool_.reserve(count);
for (std::size_t i = 0; i < count; ++i) {
pool_.push_back(std::make_unique<T>(std::forward<Args>(args)...));
}
}
T* acquire() {
if (index_ >= pool_.size()) {
return nullptr;
}
return pool_[index_++].get();
}
void release_all() {
index_ = 0;
}
std::size_t available() const {
return pool_.size() - index_;
}
};2. 无锁数据结构
#include <atomic>
#include <memory>
template<typename T>
class LockFreeQueue {
private:
struct Node {
std::shared_ptr<T> data;
std::atomic<Node*> next;
Node() : next(nullptr) {}
Node(T value) : data(std::make_shared<T>(std::move(value))), next(nullptr) {}
};
std::atomic<Node*> head_;
std::atomic<Node*> tail_;
public:
LockFreeQueue() {
Node* dummy = new Node();
head_.store(dummy);
tail_.store(dummy);
}
~LockFreeQueue() {
while (Node* old_head = head_.load()) {
head_.store(old_head->next.load());
delete old_head;
}
}
void push(T value) {
Node* new_node = new Node(std::move(value));
Node* old_tail = tail_.load();
while (true) {
Node* next = old_tail->next.load();
if (!next) {
if (old_tail->next.compare_exchange_weak(next, new_node)) {
tail_.compare_exchange_weak(old_tail, new_node);
return;
}
} else {
tail_.compare_exchange_weak(old_tail, next);
}
}
}
std::shared_ptr<T> pop() {
Node* old_head = head_.load();
while (true) {
Node* next = old_head->next.load();
if (!next) {
return std::shared_ptr<T>();
}
if (head_.compare_exchange_weak(old_head, next)) {
std::shared_ptr<T> result = next->data;
delete old_head;
return result;
}
}
}
bool empty() const {
return head_.load()->next.load() == nullptr;
}
};第五部分:未来学习方向
1. 推荐学习路径
短期(3-6个月):
- 深入学习C++20/23所有特性
- 掌握一个主流框架(Qt、Boost、POCO)
- 学习一个领域专业知识(游戏、AI、嵌入式)
中期(6-12个月):
- 参与开源C++项目
- 学习系统设计和高并发架构
- 掌握性能分析和优化技巧
长期(1-2年):
- 深入研究编译器设计和语言实现
- 学习跨语言交互(C++/Rust/Python)
- 探索新的编程范式和架构模式
2. 推荐学习资源
书籍:
- 《C++20 - The Complete Guide》
- 《Effective Modern C++》
- 《The C++ Programming Language (4th Edition)》
- 《C++ Concurrency in Action》
在线资源:
- CppReference.com
- C++ Standards Committee Papers
- C++ Weekly (YouTube)
- Meeting C++ Conference Talks
开源项目:
- Chromium
- LLVM/Clang
- MySQL
- Unreal Engine
3. 职业发展方向
技术专家路径:
- C++语言专家
- 编译器开发工程师
- 性能优化专家
- 系统架构师
领域专家路径:
- 游戏引擎开发
- 高频交易系统
- 嵌入式系统开发
- AI框架开发
今日总结
掌握的核心技术:
- ✅ C++20协程和异步编程
- ✅ 模块化编程
- ✅ 高级概念和约束编程
- ✅ 范围库和函数式编程
- ✅ 编译期计算进阶
- ✅ 内存管理和性能优化
实际应用领域:
- 游戏开发引擎框架
- 人工智能和神经网络
- 高性能计算
- 系统级编程
继续学习建议:
- 实践项目:将所学应用到实际项目中
- 参与社区:加入C++社区,参与讨论和贡献
- 持续学习:关注C++新标准和行业发展
- 跨领域学习:学习相关技术栈和工具链
恭喜完成36天C++学习路线! 🎉
你已经完成了从C++基础到高级特性的全面学习,掌握了现代C++开发的核心技能。记住:
编程是一项终身学习的技能,真正的成长来自于持续的实践和挑战。
下一步行动建议:
- 选择一个感兴趣的项目开始实践
- 参与开源社区贡献
- 建立个人技术博客或作品集
- 准备技术面试和职业发展
祝你编程之路顺利,成为一名优秀的C++开发者! 🚀
















