我想做一个带有多个参数的日志函数,我也想用我的类调用日志函数。
这是我的代码(编译器:Visual Studio 2019 或 x86-64 gcc9.2)
问题 1> 我无法理解日志功能。是否可以像这样使用折叠表达式?(此函数来自 spdlog 库)
问题 2> 如何在 Mystruct 类中使用日志功能?
log(1, MyStruct(1, 1.1f, "hello world"s)); // compiler error
#include <cstdio>
#include <iostream>
#include <string>
#include <sstream>
template<typename ... Args>
void log(int level, Args const& ... args)
{
std::ostringstream stream;
using List = int[];
(void)List {
0, ((void)(stream << args), 0) ...
};
std::cout << stream.str() << std::endl;
}
class MyStruct
{
public:
int val1 = 0;
float val2 = 0.f;
std::string val3;
MyStruct(int v1, float v2, std::string_view const& v3) : val1(v1), val2(v2), val3(v3) {};
std::string to_string() const
{
std::stringstream stream;
stream << "val1=" << val1 << ", val2=" << val2 << ",val3=" << val3;
return stream.str();
}
};
std::ostringstream& operator<< (std::ostringstream& stream, MyStruct&& val)
{
auto str = val.to_string();
std::operator <<(stream, str);
return stream;
}
void work_good()
{
using namespace std::string_literals;
log(1, 1.1f, "hello world"s);
}
void compile_error()
{
using namespace std::string_literals;
log(1, MyStruct(1, 1.1f, "hello world"s));
}
int main()
{
work_good();
}