用C++可变参数模板实现类似C语言的printf

阅读: 评论:0

用C++可变参数模板实现类似C语言的printf

用C++可变参数模板实现类似C语言的printf

在以前,C++要实现可变参数的函数,得用C语言的va_list那一套东西,直到C++11的可变参数模板诞生,正好最近在写一个日志模块,是时候了解一下可变参数模板了。

下面这个简单的Log函数,只使用##进行占位,并没有区分类型,有点像C#的{0}、{1}……

#include <iostream>
#include <sstream>
#include <string>template<typename ...Args>
void mylog(const std::string& format, const Args&... args) {std::string temp(format);mylog(temp, );
}template<typename Next, typename ...Other>
void mylog(std::string& format, const Next& next, const Other&... other) {auto index = format.find_first_of("##");if (index == std::string::npos) {mylog(format);}else {std::ostringstream oss;oss << place(index, 2, oss.str());mylog(format, );}
}void mylog(std::string& format) {std::cout << format;
}int main() {// 无占位符mylog("Hello Indian Mi fans!n"

本文发布于:2024-02-01 06:26:48,感谢您对本站的认可!

本文链接:https://www.4u4v.net/it/170674001034541.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:类似   模板   参数   语言   printf
留言与评论(共有 0 条评论)
   
验证码:

Copyright ©2019-2022 Comsenz Inc.Powered by ©

网站地图1 网站地图2 网站地图3 网站地图4 网站地图5 网站地图6 网站地图7 网站地图8 网站地图9 网站地图10 网站地图11 网站地图12 网站地图13 网站地图14 网站地图15 网站地图16 网站地图17 网站地图18 网站地图19 网站地图20 网站地图21 网站地图22/a> 网站地图23