在以前,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, args...);
}
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 << next;
format.replace(index, 2, oss.str());
mylog(format, other...);
}
}
void mylog(std::string& format) {
std::cout << format;
}
int main() {
// 无占位符
mylog("Hello Indian Mi fans!\n"