C++可变参数模板(展开参数包)

C++版本 C11 - C14

例子:

cpp 复制代码
#include "X:\Work\Share\CCode\CPlatform\Base\global_c_all.h" 

using namespace lf;
using namespace std;
 
 

//递归终止函数
void Print()
{
	_cout << _t("\n");
}

template <typename T, typename ...Args>
void Print(T first, Args... args)
{
	_cout << first;
	Print(args...);
}

void main()
{
	 	 
	int pi = 3.14;
	 
	Print("pi=", pi,"\t_Math::_e=", _Math::_e);

	Print("a=", 10, _t("\tb="), 3.14,_t("\t水果:"), lf::水果("苹果",200,"圆形"));

}
 

输出:

其中

两个函数名称必须一样:

如果想获取参数个数,可用sizeof...(args)

例如:

输出:

因为是递归调用,所以输出格式乱了,下

面是输出参数类型列表:

cpp 复制代码
#include "X:\Work\Share\CCode\CPlatform\Base\global_c_all.h" 

using namespace lf;
using namespace std;
 
 

//递归终止函数
void Print()
{
	_cout << _t("\n");
}

template <typename T, typename ...Args>
void Print(T first, Args... args)
{
	std::cout << typeid(first).name() << "\n";	 

	Print(args...);
}

void main()
{
	 	 
	int pi = 3.14;
	 
	Print("pi=", pi,"\t_Math::_e=", _Math::_e);	 

}
 

结果:

C++版本17或以上例子可用:

cpp 复制代码
#include <iostream>
using namespace std;

// 定义一个函数模板,接收任意类型的参数包并打印每个参数值
template<typename T>
void printArgs(T arg) {
    cout << "Arg value: " << arg << endl;
}

// 递归地展开参数包
template<typename... Args>
void expandPack(Args&&... args) {
    // 将args作为单个参数传入printArgs函数进行处理
    (printArgs(forward<Args>(args)), ...);
}

int main() {
    int a = 10;
    double b = 3.14;
    string c = "Hello";

    // 调用expandPack函数展开参数包
    expandPack(a, b, c);

    return 0;
}

输出:

相关推荐
言乐61 小时前
Python游戏水平测试辅助系统
开发语言·python·游戏·django·pygame
WWJA王文举8 小时前
I²C通信完整流程详解:START、地址、ACK、数据、Repeated START和STOP一次讲透
c语言·开发语言
zhanghaha13149 小时前
Python进阶教程:6_JSON 数据解析 —— 新手完全指南
开发语言·python·json
ShineWinsu9 小时前
对于C++:C++11中lambda、function、bind的解析
c++·面试·笔试·开发·lambda·bind·function
码匠许师傅9 小时前
【C++ 面试真题】聊聊 C++ 的拷贝构造与拷贝赋值
java·c++·面试
qq_4480111610 小时前
C语言中的动态内存分配
c语言·开发语言·php
旖旎夜光10 小时前
LeetCode 3:无重复字符的最长子串(滑动窗口) —— 题解
数据结构·c++·算法·leetcode·滑动窗口
汉字萌萌哒11 小时前
2024CSP-J入门级C++真题详解
开发语言·c++
arbboter11 小时前
【网络工具】NetProxy网络代理用户手册
开发语言·网络·c#·网络代理·网络异常·代理工具
hy.z_77711 小时前
【C++】13. 继承
c++