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

输出:

相关推荐
樱木Plus2 天前
深拷贝(Deep Copy)和浅拷贝(Shallow Copy)
c++
blasit4 天前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
肆忆_5 天前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星5 天前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛7 天前
delete又未完全delete
c++
端平入洛8 天前
auto有时不auto
c++
郑州光合科技余经理8 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1239 天前
matlab画图工具
开发语言·matlab
dustcell.9 天前
haproxy七层代理
java·开发语言·前端
norlan_jame9 天前
C-PHY与D-PHY差异
c语言·开发语言