现代 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


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

相关推荐
fakerth2 分钟前
【OpenHarmony】设计模式模块详解
c++·单例模式·设计模式·openharmony
qq_401700413 分钟前
C语言void*
c语言·开发语言
sg_knight4 分钟前
Python 面向对象基础复习
开发语言·python·ai编程·面向对象·模型
biter down21 分钟前
C++ 解决海量数据 TopK 问题:小根堆高效解法
c++·算法
用户66006766853923 分钟前
斐波那契数列:从递归到缓存优化的极致拆解
前端·javascript·算法
初夏睡觉29 分钟前
P1055 [NOIP 2008 普及组] ISBN 号码
算法·p1055
程芯带你刷C语言简单算法题33 分钟前
Day28~实现strlen、strcpy、strncpy、strcat、strncat
c语言·c++·算法·c
踏浪无痕1 小时前
周末拆解:QLExpress 如何做到不编译就能执行?
后端·算法·架构
一个不知名程序员www1 小时前
算法学习入门--- 树(C++)
c++·算法
毕设源码-朱学姐1 小时前
【开题答辩全过程】以 基于Java的人体骨骼健康知识普及系统为例,包含答辩的问题和答案
java·开发语言