Search code examples
c++iostreamsetw

std::setw for the whole operator<< of user-defined type


We know, that the std::setw() influence only on the next output.

So, what standard practice to align the whole operator<< of user-defined type in table output:

class A
{
    int i, j;
public:
    friend ostream& opeartor<<(ostream& out, const A& a) { 
          return << "Data: [" << i << ", " << j << "]";
    }
}

// ...
A[] as;
out << std::left;
for (unsigned i = 0; i < n; ++i)
     out << std::setw(4)  << i
         << std::setw(20) << as[i]  // !!!
         << std::setw(20) << some_strings[i]
         << some_other_classes[i] << std::endl;
out << std::right;

Solution

  • Just add a setw() method to your class:

    class A
    {
        int i, j;
        mutable int width = -1;
    
    public:
        A& setw(int n) {
            this->width = n;
            return *this;
        }
    
        friend ostream& operator<<(ostream& out, const A& a);
    };
    

    And when you print it, if you want to align, simply use it:

    int main() {
        A as[5];
        for (auto & a : as)
            cout << a.setw(15) << endl;
    }