I want to add indent during serialization of object. But since operator<<
can only contains 2
parameters:
我想在对象的序列化过程中添加缩进。但由于operator < <只能包含2个参数:< p>
struct A {
int member;
};
ostream& operator<<(ostream& str, const A& a)
{
return str;
}
Now my solution is like this:
现在我的解决方案是这样的:
struct A {
int m1;
int m2;
};
void print(const A& a, const int indent)
{
cout << string(indent, '\t') << m1 << endl;
cout << string(indent + 1, '\t') << m2 << endl;
}
Is there any better method of adding extra parameters during object serialization?
在对象序列化期间有没有更好的方法来添加额外的参数?
1 个解决方案
#1
0
You could make a tuple or pair and send it to a operator<<
function
您可以创建一个元组或对,并将其发送给运算符<< function
or you could also do something like
或者你也可以做类似的事情
std::ostream& operator<<(std::ostream& os, const A& param)
{
auto width = os.width();
auto fill = os.fill();
os << std::setfill(fill) << std::right;
os << std::setw(width) << param.m1 << std::endl;
os << std::setw(width) << fill << param.m2 << std::endl;
return os;
}
int main()
{
struct A a{1,2};
std::cout.width(4);
std::cout.fill('\t');
std::cout << a << std::endl;
}
#1
0
You could make a tuple or pair and send it to a operator<<
function
您可以创建一个元组或对,并将其发送给运算符<< function
or you could also do something like
或者你也可以做类似的事情
std::ostream& operator<<(std::ostream& os, const A& param)
{
auto width = os.width();
auto fill = os.fill();
os << std::setfill(fill) << std::right;
os << std::setw(width) << param.m1 << std::endl;
os << std::setw(width) << fill << param.m2 << std::endl;
return os;
}
int main()
{
struct A a{1,2};
std::cout.width(4);
std::cout.fill('\t');
std::cout << a << std::endl;
}