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;
}

输出:

相关推荐
测试_AI_一辰1 小时前
项目实践笔记13:多用户事实碎片 Agent 的接口测试与约束设计
开发语言·人工智能·ai编程
云小逸1 小时前
【Nmap 设备类型识别技术】整体概况
服务器·c语言·网络·c++·nmap
twj_one1 小时前
java中23种设计模式
java·开发语言·设计模式
梵刹古音1 小时前
【C语言】 跳转语句
c语言·开发语言·算法
liu****1 小时前
29.路径类dp
c++·算法·acm
阿猿收手吧!1 小时前
【C++】C++模板特化:精准定制泛型逻辑
开发语言·c++·算法
ghie90902 小时前
MATLAB中编写不平衡磁拉力方程
开发语言·matlab
C语言小火车2 小时前
Qt样式实现方式详解:六大方法全面解析
c语言·c++·qt·学习
weixin_452159552 小时前
C++与Java性能对比
开发语言·c++·算法
会叫的恐龙2 小时前
C++ 核心知识点汇总(第一日)(输入输出与变量、类型转换)
开发语言·c++