作为一个日志库的一部分,我想要能够迭代参数包,将每个值写入流中。然而,我的第一次尝试并不能编译通过。第一个错误是“error C2144: syntax error : 'int' should be preceded by '}'”。
#include <sstream>
#include <ostream>
#include <iomanip>
#include <fstream>
template <typename ...Args>
std::ostream & Write(std::ostream & o, std::initializer_list<Args...> list)
{
size_t size = list.size();
if(list.size() > 0)
{
for(size_t i = 0; i < (size - 1); i++)
o << list[i] << ", ";
o << list[i];
}
return o;
}
template<typename ...Args>
std::ostream & Write(std::ostream & o, Args...)
{
return Write(o, { Args... });
}
int main(int argc, wchar_t * argv[])
{
std::ostringstream o;
Write(o, 1, "Hello", 2, "World", 3, 1.4857);
// o should contain the string of characters "1, Hello, 2, World, 3, 1.4857"
return 0;
}
我该如何迭代每个项目并将其发送到流中?