1. 模板元編程(TMP)與編譯時計算
(1) 類型萃取與 SFINAE
-
類型萃取(Type Traits):利用模板特化在編譯時推斷類型屬性。
template<typename T> struct is_pointer { static constexpr bool value = false; };template<typename T> struct is_pointer<T*> { static constexpr bool value = true; };static_assert(is_pointer<int*>::value, "T must be a pointer");
-
SFINAE(Substitution Failure Is Not An Error):通過模板參數匹配失敗實現條件編譯。
template<typename T> auto foo(T t) -> decltype(t.serialize(), void()) { /* T 有 serialize() 方法時調用 */ }template<typename T> void foo(...) { /* 默認實現 */ }
(2) 編譯時計算(constexpr 與模板)
-
constexpr 函數:在編譯期執行計算。
constexpr int factorial(int n) {return (n <= 1) ? 1 : n * factorial(n - 1); } static_assert(factorial(5) == 120);
-
模板遞歸計算:
template<int N> struct Factorial { static constexpr int value = N * Factorial<N-1>::value; };template<> struct Factorial<0> { static constexpr int value = 1; };
2. 移動語義與完美轉發
(1) 右值引用與移動語義
- 避免深拷貝:通過移動構造函數和
std::move
轉移資源所有權。class BigData {BigData(BigData&& other) noexcept : ptr_(other.ptr_) { other.ptr_ = nullptr; }int* ptr_; };BigData a; BigData b = std::move(a); // 觸發移動構造
(2) 完美轉發(Perfect Forwarding)
- 保留參數類型:使用
std::forward
轉發參數到其他函數。template<typename... Args> void wrapper(Args&&... args) {target(std::forward<Args>(args)...); // 保持參數的值類別(左值/右值) }
3. 智能指針與資源管理
(1) 所有權管理
-
std::unique_ptr
:獨占所有權,不可復制,可移動。auto ptr = std::make_unique<int>(42); // 推薦替代 new
-
std::shared_ptr
:共享所有權,基于引用計數。auto ptr = std::make_shared<int>(42); // 引用計數 +1 auto ptr2 = ptr; // 引用計數 +2
-
std::weak_ptr
:打破循環引用,避免內存泄漏。std::weak_ptr<A> weak = shared_ptr_A; if (auto spt = weak.lock()) { /* 安全訪問 */ }
4. 并發編程與原子操作
(1) 線程與同步
-
std::thread
:跨平臺線程管理。void task() { std::cout << "Thread running\n"; } std::thread t(task); t.join();
-
互斥鎖與條件變量:
std::mutex mtx; std::unique_lock<std::mutex> lock(mtx); // RAII 風格鎖 std::condition_variable cv; cv.wait(lock, []{ return data_ready; }); // 條件等待
(2) 原子操作(Atomic)
- 無鎖編程:保證操作的原子性。
std::atomic<int> counter{0}; counter.fetch_add(1, std::memory_order_relaxed);
5. RAII(資源獲取即初始化)
- 資源自動釋放:利用對象生命周期管理資源(如文件句柄、網絡連接)。
class FileHandle { public:FileHandle(const char* filename) : file_(fopen(filename, "r")) {}~FileHandle() { if (file_) fclose(file_); } private:FILE* file_; };
6. 類型推導與現代語法
(1) auto
與 decltype
-
自動類型推導:
auto x = 42; // x 為 int auto& ref = x; // ref 為 int& const auto* ptr = &x; // ptr 為 const int*
-
decltype
推導表達式類型:int a = 10; decltype(a) b = a; // b 的類型為 int
(2) Lambda 表達式
- 匿名函數對象:
auto lambda = [](int x) -> int { return x * 2; }; std::vector<int> v = {1, 2, 3}; std::transform(v.begin(), v.end(), v.begin(), [](int x) { return x + 1; });
7. 元編程庫與工具
(1) Boost 庫
Boost.Hana
:現代 C++ 元編程庫。using namespace boost::hana; auto types = tuple_t<int, double, char>; // 類型容器
(2) std::variant
與 std::visit
- 類型安全的聯合體:
std::variant<int, double, std::string> v; v = 3.14; // 存儲 double std::visit([](auto&& arg) { std::cout << arg; }, v); // 訪問值
8. 高級調試與優化
(1) 自定義內存管理
- 重載
new
/delete
:void* operator new(size_t size) {void* p = custom_alloc(size);if (!p) throw std::bad_alloc();return p; }
(2) 內聯匯編與編譯器指令
- 嵌入匯編代碼(需謹慎):
int add(int a, int b) {asm("addl %%ebx, %%eax;" : "=a"(a) : "a"(a), "b"(b));return a; }
應用場景示例
- 高性能計算:利用模板元編程生成優化代碼,減少運行時開銷。
- 游戲引擎:通過移動語義高效管理資源(紋理、模型)。
- 分布式系統:使用原子操作實現無鎖數據結構(隊列、哈希表)。
- 嵌入式開發:通過 RAII 管理硬件資源(GPIO、定時器)。
注意事項
- 可讀性平衡:避免過度使用模板元編程導致代碼晦澀。
- 異常安全:確保資源在異常發生時正確釋放。
- 跨平臺兼容性:注意不同編譯器對特性的支持差異(如 MSVC 和 GCC)。