前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Example 1 and 2 of variadic templates

Example 1 and 2 of variadic templates

原创
作者头像
ocean@32
修改2022-11-06 13:20:32
3250
修改2022-11-06 13:20:32
举报
文章被收录于专栏:C++ STL和泛型编程

Example 1:使用递归调用打印不同类型的一系列参数,递归函数使用function template接收可变的参数。

代码语言:txt
复制
void printX() {}
template<T, typename... types>
void printX(const T& firstArg, const types&... args) {
	std::cout << firstArg;
	printX(args...);
}
另外上面的printX可以写成下面的格式,下面这种格式为泛化格式版本
template<typename... types>
void printX(const types&... args) {
	//statement
}

Example2: 使用function template + variadic templates实现printf

代码语言:txt
复制
printf("%s, %d, %c\n", "haiyang", 15, 'c');
void printf(const char *s) {
	whild(*s) {
		if ((*s == "%") && (*(++s) != "%")) { 
			printf("invalid format stting:missing arguments");
		}
		std::cout << *s++;
	}
	return;
}

template<T, typename... types>
void printf(const char* s, T value, const types&... args) {
	while(*s) {
		if ((*s == "%") && (*(++s) != "%")) {
			std::cout << value;
			printf(s, args...);
			return;
		} 
		std::cout << *s++;
	}
	return;
}

补充一个知识点,递归函数比较耗代码的存储空间,因为递归函数在转换为二进制时会被展开。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档