在以前,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小时内删除。
留言与评论(共有 0 条评论) |