现代 C++ 使用教程

std::ref

template<typename T>

auto print_type_info(const T& t) {

if constexpr (std::is_integral<T>::value) {

return t + 1;

} else {

return t + 0.001;

}

}

template<typename T = int, typename U = int>

auto add(T x, U y) -> decltype(x+y) {

return x+y;

}

// sizeof... 不定参数个数

template<typename... Ts>

void magic(Ts... args) {

std::cout << sizeof...(args) << std::endl;

}

// 1. recursive parameter unpack

template<typename T0>

void printf1(T0 value) {

std::cout << value << std::endl;

}

template<typename T, typename... Ts>

void printf1(T value, Ts... args) {

std::cout << value << std::endl;

printf1(args...);

}

template<typename T, typename... Ts>

auto printf3(T value, Ts... args) {

std::cout << value << std::endl;

(void) std::initializer_list<T>{([&args] {

std::cout << args << std::endl;

}(), value)...};

}

template<typename ... T>

auto sum(T ... t) {

return (t + ...);

}

static std::mutex mtx;

std::lock_guard<std::mutex> lock(mtx);

// pack a lambda expression that returns 7 into a std::packaged_task

std::packaged_task<int()> task([](){return 7;});

// get the future of task

std::future<int> result = task.get_future(); // run task in a thread

std::thread(std::move(task)).detach();

std::cout << "waiting...";

result.wait(); // block until future has arrived

// 限制参数是否满足指定用法

template<typename T>

concept bool Stringable = requires(T a){

{a.to_string()} -> string;

};

void print(Stringable a){

std::cout << a.to_string() << std::endl;

}

struct Person {

double height, weight;

Person(double a, double b) : height(a), weight(b) {}

string to_string(){

return "weight: "+ std::to_string(weight) + ", height: "+ std::to_string(height);

}

};

Person p(57, 170.0);

print(p); // uses concept Stringable


创作不易,小小的支持一下吧!

相关推荐
c++逐梦人3 分钟前
记忆化搜索(DFS)
算法·深度优先
阿Y加油吧3 分钟前
二分查找进阶:搜索二维矩阵 & 查找元素首尾位置 深度解析
线性代数·算法·矩阵
小则又沐风a4 分钟前
C++内存管理 C++模板
开发语言·c++
不会写DN4 分钟前
如何给 Go 语言的 TCP 聊天服务加上 ACK 可靠送达机制
开发语言·tcp/ip·golang
小李云雾8 分钟前
FastAPI 后端开发:文件上传 + 表单提交
开发语言·python·lua·postman·fastapi
SEO-狼术8 分钟前
Visualize Org Charts and Decision Trees in WinForms
算法·决策树·机器学习
UltraLAB-F10 分钟前
GPU显存不足时的分配策略:渲染与仿真的显存争夺战解决方案
图像处理·算法·3d·ai·硬件架构
llm大模型算法工程师weng15 分钟前
Python敏感词检测方案详解
开发语言·python·c#
沐苏瑶15 分钟前
Java算法之排序
java·算法·排序算法
fengci.16 分钟前
php反序列化(复习)(第二章)
android·开发语言·学习·php