是否有更好的方法在对象序列化期间添加额外的参数?

时间:2017-07-20 06:07:17

标签: c++ serialization

我想在对象序列化期间添加缩进。但由于operator<<只能包含2个参数:

struct A {
    int member;
};

ostream& operator<<(ostream& str, const A& a)
{
  return str;
}

现在我的解决方案是这样的:

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;
}

在对象序列化期间是否有更好的方法可以添加额外的参数?

1 个答案:

答案 0 :(得分:0)

您可以制作元组或对,并将其发送到operator<<函数

或者您也可以执行类似

的操作
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;
}