101. 多线程基础

#include <iostream>
#include <thread>
#include <chrono>
using namespace std;

void task(int id) {
    cout << "线程" << id << "开始工作\n";
    this_thread::sleep_for(chrono::seconds(1));
    cout << "线程" << id << "完成工作\n";
}

int main() {
    cout << "主线程开始\n";
    
    thread t1(task, 1);
    thread t2(task, 2);
    
    t1.join();
    t2.join();
    
    cout << "主线程结束\n";
    return 0;
}

102. 线程同步(互斥锁)

#include <iostream>
#include <thread>
#include <mutex>
using namespace std;

mutex mtx;
int sharedData = 0;

void increment() {
    for (int i = 0; i < 100000; ++i) {
        lock_guard<mutex> lock(mtx); // 自动加锁解锁
        ++sharedData;
    }
}

int main() {
    thread t1(increment);
    thread t2(increment);
    
    t1.join();
    t2.join();
    
    cout << "最终值: " << sharedData << endl;
    return 0;
}

103. 条件变量

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
using namespace std;

mutex mtx;
condition_variable cv;
bool ready = false;

void worker() {
    unique_lock<mutex> lock(mtx);
    cv.wait(lock, []{ return ready; });
    cout << "Worker开始工作\n";
}

int main() {
    thread t(worker);
    
    this_thread::sleep_for(chrono::seconds(1));
    {
        lock_guard<mutex> lock(mtx);
        ready = true;
    }
    cv.notify_one();
    
    t.join();
    return 0;
}

104. 文件系统操作(C++17)

#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;

int main() {
    string path = "./test_dir";
    
    // 创建目录
    if (fs::create_directory(path)) {
        cout << "目录创建成功\n";
    }
    
    // 检查文件/目录是否存在
    cout << path << " 存在? " << fs::exists(path) << endl;
    
    // 遍历目录
    for (const auto& entry : fs::directory_iterator(path)) {
        cout << entry.path() << endl;
    }
    
    // 删除目录
    fs::remove_all(path);
    return 0;
}

105. 正则表达式匹配

#include <iostream>
#include <regex>
using namespace std;

int main() {
    string text = "我的电话是123-4567-8910,邮箱是test@example.com";
    smatch matches;
    
    // 匹配电话号码
    regex phonePattern(R"(\d{3}-\d{4}-\d{4})");
    if (regex_search(text, matches, phonePattern)) {
        cout << "找到电话号码: " << matches[0] << endl;
    }
    
    // 匹配邮箱
    regex emailPattern(R"(\w+@\w+\.\w+)");
    if (regex_search(text, matches, emailPattern)) {
        cout << "找到邮箱: " << matches[0] << endl;
    }
    
    return 0;
}

106. 时间日期处理

#include <iostream>
#include <chrono>
#include <ctime>
using namespace std;
using namespace chrono;

int main() {
    // 获取当前时间点
    auto now = system_clock::now();
    time_t now_time = system_clock::to_time_t(now);
    cout << "当前时间: " << ctime(&now_time);
    
    // 计算时间差
    auto start = high_resolution_clock::now();
    this_thread::sleep_for(seconds(1));
    auto end = high_resolution_clock::now();
    auto duration = duration_cast<milliseconds>(end - start);
    cout << "耗时: " << duration.count() << "毫秒\n";
    
    return 0;
}

107. JSON解析(使用第三方库nlohmann/json)

#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;

int main() {
    // JSON字符串解析
    string jsonStr = R"({"name":"张三", "age":25, "scores":[90,85,95]})";
    auto j = json::parse(jsonStr);
    
    cout << "姓名: " << j["name"] << endl;
    cout << "年龄: " << j["age"] << endl;
    cout << "分数: ";
    for (auto score : j["scores"]) {
        cout << score << " ";
    }
    
    // 生成JSON
    json newJson;
    newJson["city"] = "北京";
    newJson["population"] = 2171;
    cout << "\n生成JSON:\n" << newJson.dump(2) << endl;
    
    return 0;
}

108. 网络编程(简易TCP客户端)

#include <iostream>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>

int main() {
    // 创建socket
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock == -1) {
        cerr << "socket创建失败\n";
        return -1;
    }
    
    // 设置服务器地址
    sockaddr_in serverAddr;
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_port = htons(8080);
    inet_pton(AF_INET, "127.0.0.1", &serverAddr.sin_addr);
    
    // 连接服务器
    if (connect(sock, (sockaddr*)&serverAddr, sizeof(serverAddr)) == -1) {
        cerr << "连接服务器失败\n";
        close(sock);
        return -1;
    }
    
    // 发送数据
    const char* msg = "Hello Server";
    send(sock, msg, strlen(msg), 0);
    
    // 接收响应
    char buffer[1024] = {0};
    recv(sock, buffer, 1024, 0);
    cout << "服务器响应: " << buffer << endl;
    
    close(sock);
    return 0;
}

109. 单元测试框架(Catch2示例)

#define CATCH_CONFIG_MAIN
#include <catch2/catch.hpp>

int add(int a, int b) {
    return a + b;
}

TEST_CASE("加法函数测试", "[math]") {
    REQUIRE(add(2, 3) == 5);
    REQUIRE(add(-1, 1) == 0);
    REQUIRE(add(0, 0) == 0);
}

TEST_CASE("边界条件测试", "[math]") {
    REQUIRE(add(INT_MAX, 1) == INT_MIN); // 溢出测试
}

110. 设计模式-单例模式(线程安全版)

#include <iostream>
#include <mutex>
using namespace std;

class Logger {
private:
    static Logger* instance;
    static mutex mtx;
    
    Logger() {} // 私有构造函数
    Logger(const Logger&) = delete;
    Logger& operator=(const Logger&) = delete;
    
public:
    static Logger* getInstance() {
        lock_guard<mutex> lock(mtx); // 线程安全
        if (!instance) {
            instance = new Logger();
        }
        return instance;
    }
    
    void log(const string& msg) {
        cout << "日志: " << msg << endl;
    }
};

Logger* Logger::instance = nullptr;
mutex Logger::mtx;

int main() {
    Logger::getInstance()->log("程序启动");
    Logger::getInstance()->log("执行操作");
    return 0;
}

111. 生产者消费者模型

#include <iostream>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
using namespace std;

queue<int> buffer;
mutex mtx;
condition_variable cv;
const int BUFFER_SIZE = 5;

void producer(int id) {
    for (int i = 0; i < 10; ++i) {
        unique_lock<mutex> lock(mtx);
        cv.wait(lock, []{ return buffer.size() < BUFFER_SIZE; });
        
        buffer.push(i);
        cout << "生产者" << id << " 生产: " << i << endl;
        
        cv.notify_all();
        this_thread::sleep_for(chrono::milliseconds(100));
    }
}

void consumer(int id) {
    while (true) {
        unique_lock<mutex> lock(mtx);
        if (cv.wait_for(lock, chrono::seconds(1), []{ return !buffer.empty(); })) {
            int val = buffer.front();
            buffer.pop();
            cout << "消费者" << id << " 消费: " << val << endl;
            cv.notify_all();
        } else {
            cout << "消费者" << id << " 超时退出" << endl;
            break;
        }
    }
}

int main() {
    thread p1(producer, 1), p2(producer, 2);
    thread c1(consumer, 1), c2(consumer, 2);
    
    p1.join(); p2.join();
    c1.join(); c2.join();
    return 0;
}

112. 线程池实现

#include <iostream>
#include <vector>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <functional>
using namespace std;

class ThreadPool {
    vector<thread> workers;
    queue<function<void()>> tasks;
    mutex mtx;
    condition_variable cv;
    bool stop = false;
    
public:
    ThreadPool(size_t threads) {
        for (size_t i = 0; i < threads; ++i) {
            workers.emplace_back([this] {
                while (true) {
                    function<void()> task;
                    {
                        unique_lock<mutex> lock(mtx);
                        cv.wait(lock, [this]{ return stop || !tasks.empty(); });
                        if (stop && tasks.empty()) return;
                        task = move(tasks.front());
                        tasks.pop();
                    }
                    task();
                }
            });
        }
    }
    
    template<class F>
    void enqueue(F&& f) {
        {
            lock_guard<mutex> lock(mtx);
            tasks.emplace(forward<F>(f));
        }
        cv.notify_one();
    }
    
    ~ThreadPool() {
        {
            lock_guard<mutex> lock(mtx);
            stop = true;
        }
        cv.notify_all();
        for (thread& worker : workers) {
            worker.join();
        }
    }
};

int main() {
    ThreadPool pool(4);
    
    for (int i = 0; i < 8; ++i) {
        pool.enqueue([i] {
            cout << "任务" << i << " 在线程" << this_thread::get_id() << "执行\n";
            this_thread::sleep_for(chrono::seconds(1));
        });
    }
    
    return 0;
}

113. 快速排序(多线程优化)

#include <iostream>
#include <vector>
#include <thread>
#include <future>
#include <algorithm>
using namespace std;

template<typename T>
void parallelQuickSort(vector<T>& data, int left, int right, int depth = 0) {
    if (left >= right) return;
    
    int i = left, j = right;
    T pivot = data[(left + right) / 2];
    
    while (i <= j) {
        while (data[i] < pivot) i++;
        while (data[j] > pivot) j--;
        if (i <= j) swap(data[i++], data[j--]);
    }
    
    if (depth < 3) { // 控制递归深度避免过度创建线程
        auto leftSort = async(launch::async, [&] {
            parallelQuickSort(data, left, j, depth + 1);
        });
        parallelQuickSort(data, i, right, depth + 1);
        leftSort.get();
    } else {
        parallelQuickSort(data, left, j, depth + 1);
        parallelQuickSort(data, i, right, depth + 1);
    }
}

int main() {
    vector<int> data = {9, 3, 7, 1, 5, 10, 2, 8, 6, 4};
    
    parallelQuickSort(data, 0, data.size() - 1);
    
    cout << "排序结果: ";
    for (int num : data) cout << num << " ";
    return 0;
}

114. 观察者模式(事件系统)

#include <iostream>
#include <vector>
#include <functional>
#include <algorithm>
using namespace std;

class EventSystem {
    using Callback = function<void(const string&)>;
    vector<Callback> listeners;
    
public:
    void subscribe(Callback cb) {
        listeners.push_back(cb);
    }
    
    void unsubscribe(const Callback& cb) {
        listeners.erase(remove(listeners.begin(), listeners.end(), cb), listeners.end());
    }
    
    void notify(const string& event) {
        for (const auto& cb : listeners) {
            cb(event);
        }
    }
};

int main() {
    EventSystem events;
    
    auto listener1 = const string& msg {
        cout << "监听器1收到: " << msg << endl;
    };
    
    auto listener2 = const string& msg {
        cout << "监听器2收到: " << msg << endl;
    };
    
    events.subscribe(listener1);
    events.subscribe(listener2);
    
    events.notify("系统启动");
    events.unsubscribe(listener1);
    events.notify("用户登录");
    
    return 0;
}

115. 策略模式(支付系统)

#include <iostream>
#include <memory>
using namespace std;

class PaymentStrategy {
public:
    virtual void pay(double amount) = 0;
    virtual ~PaymentStrategy() = default;
};

class CreditCardPayment : public PaymentStrategy {
    string cardNumber;
public:
    CreditCardPayment(const string& num) : cardNumber(num) {}
    void pay(double amount) override {
        cout << "信用卡支付 " << amount << "元 (卡号:" << cardNumber << ")\n";
    }
};

class AlipayPayment : public PaymentStrategy {
    string account;
public:
    AlipayPayment(const string& acc) : account(acc) {}
    void pay(double amount) override {
        cout << "支付宝支付 " << amount << "元 (账户:" << account << ")\n";
    }
};

class PaymentContext {
    unique_ptr<PaymentStrategy> strategy;
public:
    void setStrategy(unique_ptr<PaymentStrategy> s) {
        strategy = move(s);
    }
    
    void executePayment(double amount) {
        if (strategy) {
            strategy->pay(amount);
        } else {
            cerr << "未设置支付策略\n";
        }
    }
};

int main() {
    PaymentContext context;
    
    context.setStrategy(make_unique<CreditCardPayment>("1234-5678-9012"));
    context.executePayment(100.50);
    
    context.setStrategy(make_unique<AlipayPayment>("user@example.com"));
    context.executePayment(55.30);
    
    return 0;
}

116. 访问者模式(文档处理)

#include <iostream>
#include <vector>
using namespace std;

class DocumentVisitor;
class TextElement;
class ImageElement;

class DocumentElement {
public:
    virtual void accept(DocumentVisitor& visitor) = 0;
    virtual ~DocumentElement() = default;
};

class TextElement : public DocumentElement {
    string content;
public:
    TextElement(string c) : content(c) {}
    string getContent() const { return content; }
    void accept(DocumentVisitor& visitor) override;
};

class ImageElement : public DocumentElement {
    string path;
public:
    ImageElement(string p) : path(p) {}
    string getPath() const { return path; }
    void accept(DocumentVisitor& visitor) override;
};

class DocumentVisitor {
public:
    virtual void visit(TextElement& text) = 0;
    virtual void visit(ImageElement& image) = 0;
    virtual ~DocumentVisitor() = default;
};

void TextElement::accept(DocumentVisitor& visitor) { visitor.visit(*this); }
void ImageElement::accept(DocumentVisitor& visitor) { visitor.visit(*this); }

class WordCountVisitor : public DocumentVisitor {
    int count = 0;
public:
    void visit(TextElement& text) override {
        count += text.getContent().length();
    }
    void visit(ImageElement&) override {}
    int getCount() const { return count; }
};

class Document {
    vector<unique_ptr<DocumentElement>> elements;
public:
    void addElement(unique_ptr<DocumentElement> elem) {
        elements.push_back(move(elem));
    }
    
    template<typename Visitor>
    void applyVisitor(Visitor& visitor) {
        for (auto& elem : elements) {
            elem->accept(visitor);
        }
    }
};

int main() {
    Document doc;
    doc.addElement(make_unique<TextElement>("Hello World"));
    doc.addElement(make_unique<ImageElement>("pic.jpg"));
    doc.addElement(make_unique<TextElement>("C++ Programming"));
    
    WordCountVisitor counter;
    doc.applyVisitor(counter);
    cout << "总字符数: " << counter.getCount() << endl;
    
    return 0;
}

117. 享元模式(字符格式化)

#include <iostream>
#include <unordered_map>
using namespace std;

class TextStyle {
    string font;
    int size;
    bool bold;
public:
    TextStyle(string f, int s, bool b) : font(f), size(s), bold(b) {}
    
    void apply(const string& text) const {
        cout << "应用样式: " << font << "-" << size << (bold ? "加粗" : "") 
             << " -> " << text << endl;
    }
    
    bool operator==(const TextStyle& other) const {
        return font == other.font && size == other.size && bold == other.bold;
    }
};

class TextStyleFactory {
    unordered_map<size_t, TextStyle> styles;
    
    size_t hashStyle(const TextStyle& style) {
        return hash<string>()(style.font) ^ hash<int>()(style.size) ^ hash<bool>()(style.bold);
    }
    
public:
    const TextStyle& getStyle(const string& font, int size, bool bold) {
        TextStyle temp(font, size, bold);
        size_t key = hashStyle(temp);
        
        if (styles.find(key) == styles.end()) {
            styles.emplace(key, temp);
        }
        return styles.at(key);
    }
};

int main() {
    TextStyleFactory factory;
    
    const TextStyle& style1 = factory.getStyle("Arial", 12, false);
    const TextStyle& style2 = factory.getStyle("Times New Roman", 14, true);
    const TextStyle& style3 = factory.getStyle("Arial", 12, false); // 复用
    
    style1.apply("普通文本");
    style2.apply("重要标题");
    style3.apply("复用样式");
    
    cout << "样式1和样式3" << (style1 == style3 ? "相同" : "不同") << endl;
    return 0;
}

118. 组合模式(文件系统)

#include <iostream>
#include <vector>
#include <memory>
using namespace std;

class FileSystemComponent {
public:
    virtual void display(int indent = 0) const = 0;
    virtual ~FileSystemComponent() = default;
};

class File : public FileSystemComponent {
    string name;
public:
    File(string n) : name(n) {}
    void display(int indent) const override {
        cout << string(indent, ' ') << "📄 " << name << endl;
    }
};

class Directory : public FileSystemComponent {
    string name;
    vector<unique_ptr<FileSystemComponent>> children;
public:
    Directory(string n) : name(n) {}
    
    void addComponent(unique_ptr<FileSystemComponent> comp) {
        children.push_back(move(comp));
    }
    
    void display(int indent = 0) const override {
        cout << string(indent, ' ') << "📁 " << name << endl;
        for (const auto& child : children) {
            child->display(indent + 2);
        }
    }
};

int main() {
    auto root = make_unique<Directory>("根目录");
    
    auto docs = make_unique<Directory>("文档");
    docs->addComponent(make_unique<File>("简历.pdf"));
    docs->addComponent(make_unique<File>("笔记.txt"));
    
    auto pics = make_unique<Directory>("图片");
    pics->addComponent(make_unique<File>("头像.jpg"));
    
    root->addComponent(move(docs));
    root->addComponent(move(pics));
    root->addComponent(make_unique<File>("README.md"));
    
    root->display();
    return 0;
}

119. 备忘录模式(撤销操作)

#include <iostream>
#include <vector>
#include <memory>
using namespace std;

class DocumentMemento {
    string content;
public:
    DocumentMemento(string c) : content(c) {}
    string getContent() const { return content; }
};

class Document {
    string content;
public:
    void write(string text) { content += text; }
    string getContent() const { return content; }
    
    unique_ptr<DocumentMemento> createMemento() {
        return make_unique<DocumentMemento>(content);
    }
    
    void restoreFromMemento(const DocumentMemento* memento) {
        content = memento->getContent();
    }
};

class History {
    vector<unique_ptr<DocumentMemento>> states;
public:
    void push(unique_ptr<DocumentMemento> state) {
        states.push_back(move(state));
    }
    
    unique_ptr<DocumentMemento> pop() {
        if (states.empty()) return nullptr;
        auto last = move(states.back());
        states.pop_back();
        return last;
    }
};

int main() {
    Document doc;
    History history;
    
    doc.write("第一行文字\n");
    history.push(doc.createMemento());
    
    doc.write("第二行文字\n");
    history.push(doc.createMemento());
    
    cout << "当前文档:\n" << doc.getContent();
    
    // 撤销
    auto lastState = history.pop();
    if (lastState) {
        doc.restoreFromMemento(lastState.get());
        cout << "\n撤销后文档:\n" << doc.getContent();
    }
    
    return 0;
}

120. 状态模式(交通信号灯)

#include <iostream>
#include <memory>
using namespace std;

class TrafficLightState {
public:
    virtual void handle() = 0;
    virtual ~TrafficLightState() = default;
};

class RedState : public TrafficLightState {
public:
    void handle() override {
        cout << "红灯 - 停止\n";
    }
};

class GreenState : public TrafficLightState {
public:
    void handle() override {
        cout << "绿灯 - 通行\n";
    }
};

class YellowState : public TrafficLightState {
public:
    void handle() override {
        cout << "黄灯 - 准备\n";
    }
};

class TrafficLight {
    unique_ptr<TrafficLightState> state;
public:
    TrafficLight() : state(make_unique<RedState>()) {}
    
    void setState(unique_ptr<TrafficLightState> newState) {
        state = move(newState);
    }
    
    void change() {
        state->handle();
    }
};

int main() {
    TrafficLight light;
    
    light.change();
    light.setState(make_unique<GreenState>());
    light.change();
    light.setState(make_unique<YellowState>());
    light.change();
    light.setState(make_unique<RedState>());
    light.change();
    
    return 0;
}

121. 模板元编程-编译期阶乘

#include <iostream>
using namespace std;

template <int N>
struct Factorial {
    static const int value = N * Factorial<N - 1>::value;
};

template <>
struct Factorial<0> {
    static const int value = 1;
};

int main() {
    cout << "5! = " << Factorial<5>::value << endl;  // 输出120
    cout << "10! = " << Factorial<10>::value << endl; // 输出3628800
    return 0;
}

122. 类型萃取(判断指针类型)

#include <iostream>
#include <type_traits>
using namespace std;

template <typename T>
void checkPointer(T* ptr) {
    if (is_pointer<T*>::value) {
        cout << "是指针类型,指向: ";
        if (is_integral<T>::value) cout << "整数类型\n";
        else if (is_floating_point<T>::value) cout << "浮点类型\n";
        else cout << "其他类型\n";
    }
}

int main() {
    int* ip = nullptr;
    double* dp = nullptr;
    checkPointer(ip);
    checkPointer(dp);
    return 0;
}

123. SFINAE(替换失败不是错误)

#include <iostream>
#include <type_traits>
using namespace std;

template <typename T>
typename enable_if<is_integral<T>::value, void>::type
printNum(T num) {
    cout << "整数: " << num << endl;
}

template <typename T>
typename enable_if<is_floating_point<T>::value, void>::type
printNum(T num) {
    cout << "浮点数: " << num << endl;
}

int main() {
    printNum(42);      // 调用整数版本
    printNum(3.14);    // 调用浮点数版本
    // printNum("hello"); // 编译错误,没有匹配的函数
    return 0;
}

124. 可变参数模板

#include <iostream>
using namespace std;

// 基础情况
void printArgs() {
    cout << endl;
}

template <typename T, typename... Args>
void printArgs(T first, Args... args) {
    cout << first << " ";
    printArgs(args...);
}

template <typename... Args>
double sum(Args... args) {
    return (args + ...); // C++17折叠表达式
}

int main() {
    printArgs(1, "two", 3.0, '4'); // 输出: 1 two 3 4 
    cout << "求和: " << sum(1, 2.5, 3, 4.7) << endl; // 输出11.2
    return 0;
}

125. 编译期字符串处理

#include <iostream>
using namespace std;

template <char... Chars>
struct FixedString {
    static const char value[sizeof...(Chars) + 1];
};

template <char... Chars>
const char FixedString<Chars...>::value[] = {Chars..., '\0'};

template <typename T, T... Chars>
constexpr auto operator"" _fs() -> FixedString<Chars...> {
    return {};
}

int main() {
    auto str = "hello"_fs;
    cout << str.value << endl; // 输出hello
    
    constexpr auto compileTimeStr = FixedString<'C','+','+'>{};
    cout << compileTimeStr.value << endl; // 输出C++
    return 0;
}

126. 类型列表操作

#include <iostream>
#include <type_traits>
using namespace std;

// 空类型列表
struct NullType {};

template <typename... Types>
struct TypeList {
    using Head = NullType;
    using Tail = NullType;
};

template <typename Head, typename... Tail>
struct TypeList<Head, Tail...> {
    using Head = Head;
    using Tail = TypeList<Tail...>;
};

// 获取第N个类型
template <typename List, unsigned N>
struct GetType {
    using type = typename GetType<typename List::Tail, N - 1>::type;
};

template <typename List>
struct GetType<List, 0> {
    using type = typename List::Head;
};

int main() {
    using MyList = TypeList<int, double, char, string>;
    
    cout << "第一个类型: " << typeid(MyList::Head).name() << endl;
    cout << "第三个类型: " << typeid(GetType<MyList, 2>::type).name() << endl;
    
    return 0;
}

127. 编译期判断类型是否可哈希

#include <iostream>
#include <functional>
#include <type_traits>
using namespace std;

template <typename T>
struct is_hashable {
    template <typename U>
    static auto test(U* u) -> decltype(hash<U>()(*u), true_type());
    
    static auto test(...) -> false_type;
    
    static const bool value = decltype(test((T*)nullptr))::value;
};

struct UnhashableType {};

int main() {
    cout << boolalpha;
    cout << "int可哈希? " << is_hashable<int>::value << endl;
    cout << "string可哈希? " << is_hashable<string>::value << endl;
    cout << "UnhashableType可哈希? " << is_hashable<UnhashableType>::value << endl;
    return 0;
}

128. 编译期字符串加密

#include <iostream>
using namespace std;

template <char... Chars>
struct EncryptedString {
    static constexpr char value[sizeof...(Chars) + 1] = {
        (Chars ^ 0x55)..., '\0' // 简单异或加密
    };
    
    static auto decrypt() {
        return FixedString<(Chars ^ 0x55)...>{};
    }
};

template <typename T, T... Chars>
constexpr auto operator"" _enc() -> EncryptedString<Chars...> {
    return {};
}

int main() {
    auto secret = "Hello"_enc;
    cout << "加密后: " << secret.value << endl;
    cout << "解密后: " << secret.decrypt().value << endl;
    return 0;
}

129. 编译期素数判断

#include <iostream>
using namespace std;

template <int N, int D = N / 2>
struct IsPrime {
    static const bool value = (N % D != 0) && IsPrime<N, D - 1>::value;
};

template <int N>
struct IsPrime<N, 1> {
    static const bool value = true;
};

template <>
struct IsPrime<1, 1> {
    static const bool value = false;
};

int main() {
    cout << boolalpha;
    cout << "2是素数? " << IsPrime<2>::value << endl;
    cout << "17是素数? " << IsPrime<17>::value << endl;
    cout << "20是素数? " << IsPrime<20>::value << endl;
    return 0;
}

130. 编译期字符串反转

#include <iostream>
using namespace std;

template <typename T>
struct ReverseString;

template <char... Chars>
struct ReverseString<FixedString<Chars...>> {
    using type = FixedString<Chars...>;
};

template <char First, char... Rest>
struct ReverseString<FixedString<First, Rest...>> {
    using type = typename ReverseString<FixedString<Rest...>>::type::template append<First>;
};

template <char... Chars>
struct FixedString {
    template <char C>
    using append = FixedString<Chars..., C>;
    
    static const char value[sizeof...(Chars) + 1];
};

template <char... Chars>
const char FixedString<Chars...>::value[] = {Chars..., '\0'};

int main() {
    using Original = FixedString<'H','e','l','l','o'>;
    using Reversed = ReverseString<Original>::type;
    
    cout << "原始: " << Original::value << endl;
    cout << "反转: " << Reversed::value << endl;
    return 0;
}

131. 协程基础(C++20)

#include <iostream>
#include <coroutine>
using namespace std;

struct Generator {
    struct promise_type {
        int current_value;
        
        Generator get_return_object() {
            return Generator{coroutine_handle<promise_type>::from_promise(*this)};
        }
        suspend_always initial_suspend() { return {}; }
        suspend_always final_suspend() noexcept { return {}; }
        void return_void() {}
        suspend_always yield_value(int value) {
            current_value = value;
            return {};
        }
        void unhandled_exception() { terminate(); }
    };

    coroutine_handle<promise_type> coro;
    
    explicit Generator(coroutine_handle<promise_type> h) : coro(h) {}
    ~Generator() { if (coro) coro.destroy(); }
    
    int next() {
        coro.resume();
        return coro.promise().current_value;
    }
};

Generator range(int from, int to) {
    for (int i = from; i <= to; ++i) {
        co_yield i;
    }
}

int main() {
    auto gen = range(1, 5);
    while (true) {
        int val = gen.next();
        cout << val << " ";
        if (val == 5) break;
    }
    return 0;
}

132. 原子操作与内存序

#include <iostream>
#include <atomic>
#include <thread>
using namespace std;

atomic<int> counter(0);

void increment(int n) {
    for (int i = 0; i < n; ++i) {
        counter.fetch_add(1, memory_order_relaxed);
    }
}

int main() {
    thread t1(increment, 100000);
    thread t2(increment, 100000);
    
    t1.join();
    t2.join();
    
    cout << "计数器: " << counter.load() << endl;
    return 0;
}

133. 并行算法(C++17)

#include <iostream>
#include <vector>
#include <algorithm>
#include <execution>
using namespace std;

int main() {
    vector<int> nums(1000000);
    iota(nums.begin(), nums.end(), 0);
    
    // 并行排序
    sort(execution::par, nums.begin(), nums.end());
    
    // 并行变换
    transform(execution::par, 
        nums.begin(), nums.end(), nums.begin(),
        int n { return n * n; });
    
    cout << "前5个元素: ";
    for (int i = 0; i < 5; ++i) cout << nums[i] << " ";
    return 0;
}

134. 概念约束(C++20)

#include <iostream>
#include <concepts>
using namespace std;

template <typename T>
concept Addable = requires(T a, T b) {
    { a + b } -> same_as<T>;
};

template <Addable T>
T sum(T a, T b) {
    return a + b;
}

struct Point {
    int x, y;
    Point operator+(Point other) const {
        return {x + other.x, y + other.y};
    }
};

int main() {
    cout << sum(3, 5) << endl;       // 正确
    cout << sum(Point{1,2}, Point{3,4}).x << endl; // 正确
    // sum("a", "b"); // 编译错误,字符串不满足Addable
    return 0;
}

135. 结构化绑定(C++17)

#include <iostream>
#include <tuple>
#include <map>
using namespace std;

struct Person {
    string name;
    int age;
};

tuple<string, int> getPerson() {
    return {"张三", 25};
}

int main() {
    // 结构体分解
    Person p{"李四", 30};
    auto [name, age] = p;
    cout << name << " " << age << endl;
    
    // 元组分解
    auto [n, a] = getPerson();
    cout << n << " " << a << endl;
    
    // map遍历
    map<string, int> scores = {{"数学", 90}, {"语文", 85}};
    for (const auto& [subject, score] : scores) {
        cout << subject << ": " << score << endl;
    }
    return 0;
}

136. if constexpr编译期分支

#include <iostream>
#include <type_traits>
using namespace std;

template <typename T>
void process(T value) {
    if constexpr (is_pointer_v<T>) {
        cout << "处理指针: " << *value << endl;
    } 
    else if constexpr (is_integral_v<T>) {
        cout << "处理整数: " << value * 2 << endl;
    }
    else {
        cout << "通用处理: " << value << endl;
    }
}

int main() {
    int num = 42;
    process(num);
    process(&num);
    process(3.14);
    return 0;
}

137. 变参模板展开技巧

#include <iostream>
#include <string>
using namespace std;

template <typename... Args>
void printAll(Args... args) {
    (cout << ... << args) << endl; // 折叠表达式(C++17)
}

template <typename... Args>
auto sumAll(Args... args) {
    return (args + ...); // 求和折叠
}

template <typename... Args>
auto avg(Args... args) {
    return (args + ...) / sizeof...(args);
}

int main() {
    printAll(1, " + ", 2, " = ", 3); // 输出: 1 + 2 = 3
    cout << "求和: " << sumAll(1, 2, 3, 4) << endl;
    cout << "平均: " << avg(1.0, 2.0, 3.0, 4.0) << endl;
    return 0;
}

138. 自定义字面量(C++11)

#include <iostream>
#include <string>
#include <cmath>
using namespace std;

// 长度单位转换
constexpr long double operator"" _km(long double km) {
    return km * 1000;
}

constexpr long double operator"" _m(long double m) {
    return m;
}

constexpr long double operator"" _cm(long double cm) {
    return cm / 100;
}

// 二进制字面量
constexpr unsigned long long operator"" _bin(const char* str, size_t) {
    unsigned long long value = 0;
    for (; *str; ++str) {
        value = value * 2 + (*str - '0');
    }
    return value;
}

int main() {
    cout << "1公里 = " << 1.0_km << "米\n";
    cout << "50厘米 = " << 50.0_cm << "米\n";
    cout << "二进制1101 = " << "1101"_bin << endl;
    return 0;
}

139. 类型擦除技术

#include <iostream>
#include <memory>
#include <vector>
using namespace std;

class Drawable {
    struct Concept {
        virtual ~Concept() = default;
        virtual void draw() const = 0;
    };
    
    template <typename T>
    struct Model : Concept {
        T obj;
        Model(T o) : obj(move(o)) {}
        void draw() const override { obj.draw(); }
    };
    
    unique_ptr<Concept> object;
public:
    template <typename T>
    Drawable(T obj) : object(make_unique<Model<T>>(move(obj))) {}
    
    void draw() const { object->draw(); }
};

struct Circle {
    void draw() const { cout << "画圆形\n"; }
};

struct Square {
    void draw() const { cout << "画方形\n"; }
};

int main() {
    vector<Drawable> shapes;
    shapes.emplace_back(Circle{});
    shapes.emplace_back(Square{});
    
    for (const auto& shape : shapes) {
        shape.draw();
    }
    return 0;
}

140. 编译期字符串拼接

#include <iostream>
using namespace std;

template <typename... Strings>
class Concat {
    static constexpr size_t len = (0 + ... + Strings::length);
    char buffer[len + 1] = {};
    
public:
    Concat() {
        char* ptr = buffer;
        ((ptr = copy(ptr, Strings::data)), ...);
    }
    
    static char* copy(char* dst, const char* src) {
        while (*src) *dst++ = *src++;
        return dst;
    }
    
    const char* c_str() const { return buffer; }
    size_t length() const { return len; }
};

template <typename... Strings>
Concat<Strings...> concat(Strings...) {
    return {};
}

int main() {
    auto str = concat("Hello", " ", "World", "!");
    cout << str.c_str() << endl; // 输出: Hello World!
    cout << "长度: " << str.length() << endl;
    return 0;
}

141. 编译期类型列表过滤

#include <iostream>
#include <type_traits>
using namespace std;

template <typename... Ts>
struct TypeList {};

template <typename List, template<typename> class Pred>
struct Filter;

template <template<typename> class Pred, typename... Ts>
struct Filter<TypeList<Ts...>, Pred> {
    using type = TypeList<>;
};

template <template<typename> class Pred, typename T, typename... Ts>
struct Filter<TypeList<T, Ts...>, Pred> {
    using tail = typename Filter<TypeList<Ts...>, Pred>::type;
    using type = conditional_t<
        Pred<T>::value,
        typename tail::template prepend<T>,
        tail
    >;
};

// 测试谓词
template <typename T>
struct IsIntegral : integral_constant<bool, is_integral<T>::value> {};

int main() {
    using MyTypes = TypeList<int, float, char, double, short>;
    using Filtered = Filter<MyTypes, IsIntegral>::type;
    
    cout << "过滤后保留" << sizeof...(Filtered::types) << "个整型" << endl;
    return 0;
}

142. 编译期字符串加密(AES模拟)

#include <iostream>
using namespace std;

template <char... Chars>
struct EncryptedString {
    static constexpr char key = 0x55;
    static constexpr char value[sizeof...(Chars) + 1] = {
        (Chars ^ key)..., '\0'
    };
    
    static constexpr auto decrypt() {
        return EncryptedString<(Chars ^ key)...>{};
    }
};

template <typename T, T... Chars>
constexpr auto operator"" _aes() {
    return EncryptedString<Chars...>{};
}

int main() {
    constexpr auto secret = "SecretMessage"_aes;
    cout << "加密: " << secret.value << endl;
    cout << "解密: " << secret.decrypt().value << endl;
    return 0;
}

143. 模式匹配(C++模拟)

#include <iostream>
#include <variant>
using namespace std;

template <typename... Cases>
struct Matcher {
    template <typename T>
    static auto match(T&& value) {
        return (Cases::match(value) || ...);
    }
};

struct IntCase {
    static bool match(int i) {
        cout << "匹配到整数: " << i << endl;
        return true;
    }
};

struct StringCase {
    static bool match(const string& s) {
        cout << "匹配到字符串: " << s << endl;
        return true;
    }
};

template <typename T>
void patternMatch(T&& value) {
    Matcher<IntCase, StringCase>::match(value);
}

int main() {
    patternMatch(42);
    patternMatch("hello"s);
    return 0;
}

144. 编译期JSON解析(简化版)

#include <iostream>
#include <string_view>
using namespace std;

template <char... Chars>
struct JsonString {
    static constexpr string_view value{Chars..., '\0'};
};

template <typename T, T... Chars>
constexpr auto operator"" _json() {
    return JsonString<Chars...>{};
}

int main() {
    constexpr auto json = R"({"name":"Alice","age":25})"_json;
    cout << "JSON: " << json.value << endl;
    return 0;
}

145. 编译期矩阵运算

#include <iostream>
using namespace std;

template <size_t Rows, size_t Cols, typename T = int>
struct Matrix {
    T data[Rows][Cols] = {};
    
    constexpr Matrix(initializer_list<initializer_list<T>> init) {
        size_t i = 0;
        for (auto& row : init) {
            size_t j = 0;
            for (auto& val : row) {
                data[i][j++] = val;
            }
            if (++i == Rows) break;
        }
    }
    
    template <size_t OtherCols>
    constexpr auto operator*(const Matrix<Cols, OtherCols, T>& other) const {
        Matrix<Rows, OtherCols, T> result;
        for (size_t i = 0; i < Rows; ++i) {
            for (size_t j = 0; j < OtherCols; ++j) {
                for (size_t k = 0; k < Cols; ++k) {
                    result.data[i][j] += data[i][k] * other.data[k][j];
                }
            }
        }
        return result;
    }
};

int main() {
    constexpr Matrix<2, 3> A = {{1, 2, 3}, {4, 5, 6}};
    constexpr Matrix<3, 2> B = {{7, 8}, {9, 10}, {11, 12}};
    constexpr auto C = A * B;
    
    cout << "矩阵乘法结果:\n";
    for (size_t i = 0; i < 2; ++i) {
        for (size_t j = 0; j < 2; ++j) {
            cout << C.data[i][j] << " ";
        }
        cout << endl;
    }
    return 0;
}

146. 编译期单位换算

#include <iostream>
using namespace std;

template <typename T, T Val, T Factor>
struct Unit {
    static constexpr T value = Val;
    static constexpr T factor = Factor;
    
    constexpr operator T() const { return value; }
    
    template <T NewFactor>
    constexpr auto convert() const {
        return Unit<T, value * factor / NewFactor, NewFactor>{};
    }
};

template <typename T, T Val>
using Meter = Unit<T, Val, 1>;

template <typename T, T Val>
using Kilometer = Unit<T, Val, 1000>;

int main() {
    constexpr Kilometer<int, 5> km;
    constexpr auto m = km.convert<1>();
    
    cout << km << "公里 = " << m << "米\n";
    return 0;
}

147. 编译期FizzBuzz

#include <iostream>
using namespace std;

template <int N>
struct FizzBuzz {
    static void print() {
        FizzBuzz<N-1>::print();
        if constexpr (N % 15 == 0) cout << "FizzBuzz\n";
        else if constexpr (N % 3 == 0) cout << "Fizz\n";
        else if constexpr (N % 5 == 0) cout << "Buzz\n";
        else cout << N << "\n";
    }
};

template <>
struct FizzBuzz<0> {
    static void print() {}
};

int main() {
    FizzBuzz<30>::print();
    return 0;
}

148. 编译期CRC32校验

#include <iostream>
using namespace std;

template <unsigned N, unsigned C = 0>
struct Crc32 {
    static constexpr unsigned value = 
        Crc32<N/256, (C >> 8) ^ (0xEDB88320 & ~((C & 1)-1))>::value;
};

template <unsigned C>
struct Crc32<0, C> {
    static constexpr unsigned value = C;
};

template <char... Chars>
struct StringCrc {
    static constexpr unsigned value = 
        (Crc32<static_cast<unsigned>(Chars)>::value ^ ...);
};

int main() {
    constexpr auto crc = StringCrc<'H','e','l','l','o'>::value;
    cout << "CRC32('Hello') = " << hex << crc << endl;
    return 0;
}

149. 反射模拟(成员遍历)

#include <iostream>
#include <string>
#include <tuple>
using namespace std;

struct Person {
    string name;
    int age;
    double height;
};

template <typename T>
void reflectMembers(T& obj) {
    cout << "对象类型: " << typeid(T).name() << endl;
    cout << "成员数量: " << tuple_size<decltype(T::members)>::value << endl;
    
    [&]<size_t... I>(index_sequence<I...>) {
        (..., (cout << get<I>(T::members).name << ": " 
                   << get<I>(T::members).getter(obj) << endl));
    }(make_index_sequence<tuple_size<decltype(T::members)>::value>{});
}

template <>
constexpr auto Person::members = make_tuple(
    Member{"name", Person& p -> auto& { return p.name; }},
    Member{"age", Person& p -> auto& { return p.age; }},
    Member{"height", Person& p -> auto& { return p.height; }}
);

int main() {
    Person p{"Alice", 25, 165.5};
    reflectMembers(p);
    return 0;
}

150. 编译期Brainfuck解释器

#include <iostream>
#include <array>
using namespace std;

template <size_t N, typename Code>
struct Brainfuck {
    array<char, 30000> memory{};
    size_t ptr = 0;
    
    void execute(const Code& code) {
        size_t pc = 0;
        while (pc < code.size()) {
            switch (code[pc]) {
                case '>': ++ptr; break;
                case '<': --ptr; break;
                case '+': ++memory[ptr]; break;
                case '-': --memory[ptr]; break;
                case '.': cout << memory[ptr]; break;
                case ',': cin >> memory[ptr]; break;
                case '[': 
                    if (!memory[ptr]) {
                        int depth = 1;
                        while (depth > 0) {
                            ++pc;
                            if (code[pc] == '[') ++depth;
                            if (code[pc] == ']') --depth;
                        }
                    }
                    break;
                case ']':
                    if (memory[ptr]) {
                        int depth = 1;
                        while (depth > 0) {
                            --pc;
                            if (code[pc] == ']') ++depth;
                            if (code[pc] == '[') --depth;
                        }
                    }
                    break;
            }
            ++pc;
        }
    }
};

int main() {
    constexpr string_view code = "++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>.+++++++..+++.>>.<-.<.+++..--.>>+.>++.";
    Brainfuck<30000, decltype(code)> interpreter;
    interpreter.execute(code);
    return 0;
}
Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐