Jonathan Castro
Jonathan Castro

Reputation: 73

std::basic_ostream with parameter

I would like to know how can I insert a parameter in a std::basic_ostream I've been trying but I can't

I need to insert a parameter to select which values from arista I want to print Once I have the parameter inserted the next step is easy because it is just an if condition

template <typename charT>
friend std::basic_ostream<charT> &operator << (
    std::basic_ostream<charT>& out, Familia &familia
    ) {
    out << "\t Relaciones\n";
    for (Vertice<cedula, relacion> &vertice : familia) {
        int per = vertice.getFuente();
        for (Arista<cedula, relacion> &arista : vertice) {
            out << per << "->";
            out << arista.getDestino() << " es" << " " << arista.getValor() << "\n";
        }
    }
    return out;
}

Upvotes: 0

Views: 206

Answers (1)

There are ways in which you can add custom behavior and state to the standard stream classes via stream manipulators.

But I personally feel this is too much overhead. What I suggest is that you define a new type that accepts the parameter and Familia reference, and then proceeds to print:

class FormattedFamilia {
  Familia const& _to_print;
  int _parameter;
public:
  FormattedFamilia(int parameter, Familia const& to_print)
    : _parameter(parameter), _to_print(to_print)
  {}

  template <typename charT>
  friend std::basic_ostream<charT> &operator << (
    std::basic_ostream<charT>& out, FormattedFamilia const & ff
  ) {
     if(_parameter > 0) {
       // do printing using out.
     }
  }
};

It would have to be a friend class of Familia, of course. And using it would be as simple as this:

cout << FormattedFamilia(7, familia);

Upvotes: 2

Related Questions