C++11 - 6 - 可变参数模板

c++

前言:

Vue框架:从项目学Vue
OJ算法系列:神机百炼 - 算法详解
Linux操作系统:风后奇门 - linux

可变参数模板:

以往的可变参数:

printf():

  • printf()可以按照指定格式打印,参数数目不定
printf("%d %s %c %u", 1, "aaa", 'a', -1);

main():

  • main()函数的调用机制:
  1. OS调用加载器,
  2. 加载器调用mainCRCStartup()函数,
  3. mainCRCStartup()函数调用main()函数
  4. 如果任务代码没有出问题,那么虽然main进程结束,但是return 的 0就会被mainCRCStartup()接收
  • main()函数命令行参数:
int main(int argc, char* argv[], char* envp[]){
    
    
	/*
		argc统计命令行参数个数
		argv存储命令行参数,以nullptr结尾
		envp存储环境变量,以nullptr结尾
	*/
}

如今的定义:

  • 定义方式:
template <class ... Args>	//定义可变参数模板
void ShowList(Args ... args){
    
    	//使用可变参数模板
	//函数体
};
  • 参数包内参数个数:

    可以使用sizeof()获取参数包内参数个数

void ShowList(Args ... args){
    
    
	for(size_t i=0; i<size_of...(Args); i++){
    
    
		cout<<args[i]<<"   ";
		//报错:必须在上下文中扩展参数包
		//主要原因是参数包内参数类太复杂
	}
}

使用方式:

数组+推导:

  • 数组展开:
#include <iostream>
#include <typeinfo>
using namespace std;
template<class T>
void PrintArg(T t){
    
    
	cout<<typeid(T).name()<<":"<<t<<endl;
}

template <class ...Args>
void ShowList(Args... args){
    
    
	int arr[] = {
    
    (PrintArg(args), 0)...};
	cout<<endl;
}
int main(){
    
    
	cout<<"循环打印"<<endl;
	ShowList(1, 'A', string("sort"));
	return 0;
}
  • 数组说明:
    1. 每个括号都是一个逗号表达式,返回最右侧int
    2. 参数包展开成为多个逗号表达式,需要用数组接收返回值
  • …说明:
    1. 依次递增
    2. (PrintArg(args), 0)
    3. (PrintArg(args), 1)
    4. (PrintArg(args), 2)
    5. (PrintArg(args), 3)

重载+递归:

  • 逐个展开参数包,最终只剩一个参数时换其他调用函数:
#include <iostream>
#include <typeinfo>
using namespace std;
template <class T>
void Show(T t){
    
    
	cout<<typeid(T).name() <<":"<<t<<endl;
} 
template <class T, class ... Args>
void Show(T t, Args ... args){
    
    
	cout<<typeid(T).name() <<":" <<t<<endl;
	Show(args...);
}
int main(){
    
    
	cout<<"递归打印"<<endl;
	Show(1);
	Show(1, 'A');
	Show(1, 'A', string("sort"));
	return 0;
}
  • 以{1, ‘A’, string(“sort”)}分析递归过程:
  1. 参数大于一个时:调用Show(T t, Args … args);
    1. 1作为变量t被打印出来, ‘A’,string(“sort”)被包装为新的args
    2. 'A’作为变量t被打印出来,string(“sort”)被包装为新的args
  2. 参数等于一个时:调用Show(T t)
    1. string(“sort”)作为变量t被打印出来

猜你喜欢

转载自blog.csdn.net/buptsd/article/details/126895841
今日推荐