可变参数模板

  1. sizeof...计算参数个数
cpp 复制代码
template<typename... Ts>
void magic(Ts... args) {
    std::cout << sizeof...(args) << std::endl;
}

2.递归模板函数

cpp 复制代码
template<typename T>
void printf1(T value) {
    std::cout << value << std::endl;
}

template<typename T, typename... Ts>
void printf1(T value, Ts... args) {
    std::cout <<"剩余参数:" <<sizeof...(args)<< "," << value << std::endl;
    printf1(args...);
}

int main() {
    printf1(1, 2, "123", 1.1);
    return 0;
}

3.C++17 中增加了变参模板展开的支持

cpp 复制代码
//C++17 中增加了变参模板展开的支持
template<typename T0, typename... T>
void printf2(T0 t0, T... t) {
    std::cout << t0 << std::endl;
    if constexpr (sizeof...(t) > 0) printf2(t...);
}

4.初始化列表展开

cpp 复制代码
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)...};
}
相关推荐
不穿格子的程序员6 分钟前
从零开始写算法——二分-搜索二维矩阵
线性代数·算法·leetcode·矩阵·二分查找
龙泉寺天下行走37 分钟前
MinGW-w64 工具链(GCC 编译器) 的不同构建版本的区别
c++
Kuo-Teng1 小时前
LeetCode 19: Remove Nth Node From End of List
java·数据结构·算法·leetcode·链表·职场和发展·list
P***25391 小时前
前端构建工具缓存清理,npm cache与yarn cache
前端·缓存·npm
Kuo-Teng1 小时前
LeetCode 21: Merge Two Sorted Lists
java·算法·leetcode·链表·职场和发展
好奇的菜鸟1 小时前
解决 npm 依赖版本冲突:从 “unable to resolve dependency tree“ 到依赖管理高手
前端·npm·node.js
lcc1871 小时前
Vue 内置指令
前端·vue.js
代码AC不AC1 小时前
【C++】异常
c++·学习·异常
2301_800399721 小时前
stm32 printf重定向到USART
java·stm32·算法
小龙报1 小时前
《嵌入式成长系列之51单片机 --- Keil5创建工程》
c语言·开发语言·c++·单片机·嵌入式硬件·51单片机·学习方法