Modern C++ code snippets

目录

[1. 限制模板函数的模板参数类型](#1. 限制模板函数的模板参数类型)

[2. CRTP (Curiously Recurring Template Pattern)](#2. CRTP (Curiously Recurring Template Pattern))

[3. 元编程+insights](#3. 元编程+insights)

[4. 完美转发](#4. 完美转发)

[5. 工厂模式](#5. 工厂模式)

[6. Lamdba表达式](#6. Lamdba表达式)

[7. RAII - 自动释放资源](#7. RAII - 自动释放资源)

[8. 其它小伎俩](#8. 其它小伎俩)


1. 限制模板函数的模板参数类型

cpp 复制代码
#include <iostream>
#include <type_traits>

// Expected class type
class MyClass {};

// Function template using std::enable_if to check if the type is MyClass
template<typename T>
typename std::enable_if<std::is_same<T, MyClass>::value, void>::type
checkType() {
    std::cout << "Type is MyClass" << std::endl;
}

int main() {
    checkType<int>(); // Won't compile, int is not MyClass
    checkType<MyClass>(); // Will compile and print "Type is MyClass"
    return 0;
}

2. CRTP (Curiously Recurring Template Pattern)

cpp 复制代码
template <typename Derived>
struct Base {
    void interface() {
        static_cast<Derived*>(this)->implementation();
    }
};

struct Derived : Base<Derived> {
    void implementation() {
        // Implementation details
    }
};

// Usage
Derived d;
d.interface(); // Calls Derived::implementation()

CRTP + std::enable_shared_from_this<>

cpp 复制代码
class Test: public std::enable_shared_from_this<Test>
{
    std::shared_ptr<Test> GetPtr(){
        return shared_from_this();
    }

    static std::shared_ptr<Test> Create(){
        return std::shared_ptr<Test>(new Test());
    }

   private://imply constructor, so you couldn't create a object pointed by Test*
    Test() = default;
};

3. 元编程+insights

cpp 复制代码
template <int N>
struct Factorial {
    static const int value = N * Factorial<N - 1>::value;
};

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

// Usage
int result = Factorial<5>::value; // result = 120

元编程不易理解,有个在线平台可以看到模板展开的样子

4. 完美转发

cpp 复制代码
#include <iostream>
#include <utility>

void process(int& value) {
    std::cout << "L-value reference: " << value << std::endl;
}

void process(int&& value) {
    std::cout << "R-value reference: " << value << std::endl;
}

template<typename T>
void forward(T&& value) {
    process(std::forward<T>(value));
}

// Usage
int a = 5;
forward(a); // Output: L-value reference: 5
forward(10); // Output: R-value reference: 10

5. 工厂模式

cpp 复制代码
#include <iostream>

class Product {
public:
    virtual void printInfo() = 0;
};

class ConcreteProduct : public Product {
public:
    void printInfo() override {
        std::cout << "Concrete Product" << std::endl;
    }
};

class Factory {
public:
    virtual Product* createProduct() = 0;
};

class ConcreteFactory : public Factory {
public:
    Product* createProduct() override {
        return new ConcreteProduct();
    }
};

6. Lamdba表达式

cpp 复制代码
#include <iostream>

void exampleLambda() {
    int increment = 5;
    auto addIncrement = [increment](int x) { return x + increment; };
    std::cout << addIncrement(10) << std::endl; // Output: 15
}

7. RAII - 自动释放资源

cpp 复制代码
#include <iostream>
#include <fstream>
#include <string>
#include <stdexcept>

class FileResource {
public:
    explicit FileResource(const std::string& filename)
        : fileStream(filename) {
        if (!fileStream.is_open()) {
            throw std::runtime_error("Unable to open file");
        }
        std::cout << "File opened: " << filename << std::endl;
    }

    ~FileResource() {
        if (fileStream.is_open()) {
            fileStream.close();
            std::cout << "File closed" << std::endl;
        }
    }

    void writeToFile(const std::string& data) {
        fileStream << data << std::endl;
    }

private:
    std::ofstream fileStream;
};

int main() {
    try {
        FileResource file("example.txt");
        file.writeToFile("Hello, RAII!");
        // File automatically closed when 'file' goes out of scope
    } catch (const std::exception& e) {
        std::cerr << "Exception: " << e.what() << std::endl;
    }
    return 0;
}

此思想经常用来加解锁。

8. 其它小伎俩

cpp 复制代码
int mi = std::min({x1, x2, x3, x4});

#include <bits/stdc++.h>   //all headers in one

auto 

emplace_back is better than push_back

std::tuple<int, char, std::string> tp = std::make_tuple(1,'a',"bc");
std::cout<<std::get<0>(tp);
auto [i,c,s] = tp; //c++17

//deep copy
std::copy_n(arr1,n,arr2);

std::all_of
std::any_of
std::none_of

未完待续。。。

相关推荐
Biomamba生信基地2 分钟前
R语言基础| 回归分析
开发语言·回归·r语言
黑客-雨16 分钟前
从零开始:如何用Python训练一个AI模型(超详细教程)非常详细收藏我这一篇就够了!
开发语言·人工智能·python·大模型·ai产品经理·大模型学习·大模型入门
Pandaconda21 分钟前
【Golang 面试题】每日 3 题(三十九)
开发语言·经验分享·笔记·后端·面试·golang·go
半盏茶香22 分钟前
扬帆数据结构算法之雅舟航程,漫步C++幽谷——LeetCode刷题之移除链表元素、反转链表、找中间节点、合并有序链表、链表的回文结构
数据结构·c++·算法
加油,旭杏25 分钟前
【go语言】变量和常量
服务器·开发语言·golang
行路见知25 分钟前
3.3 Go 返回值详解
开发语言·golang
xcLeigh29 分钟前
WPF实战案例 | C# WPF实现大学选课系统
开发语言·c#·wpf
哎呦,帅小伙哦30 分钟前
Effective C++ 规则41:了解隐式接口和编译期多态
c++·effective c++
NoneCoder39 分钟前
JavaScript系列(38)-- WebRTC技术详解
开发语言·javascript·webrtc
关关钧1 小时前
【R语言】数学运算
开发语言·r语言