2017-07-20 3 views
0

オブジェクトの直列化中にインデントを追加したい。しかし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; 
} 

オブジェクトのシリアル化中に追加のパラメータを追加し、任意のより良い方法はありますか?

答えて

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; 
} 
のような何かができる可能性が
関連する問題