0

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;
}
bolov
  • 72,283
  • 15
  • 145
  • 224
  • it's not clear what are you asking. You seem to be inserting into the ostream just fine. Do you get an error? What is the exact problem? – bolov Aug 08 '17 at 07:29
  • 2
    Perhaps create a filter-function which returns an instance of a `Familia` object containing only the information you need? Or you could see how [standard manipulators](http://en.cppreference.com/w/cpp/io/manip) like for example [`setw`](http://en.cppreference.com/w/cpp/io/manip/setw) works, and model a solution based on that? – Some programmer dude Aug 08 '17 at 07:30
  • oh, now I get it. Here, have a look at these: https://stackoverflow.com/questions/799599/c-custom-stream-manipulator-that-changes-next-item-on-stream , https://stackoverflow.com/questions/15053753/writing-a-manipulator-for-a-custom-stream-class , https://stackoverflow.com/questions/1328568/custom-stream-manipulator-for-class – bolov Aug 08 '17 at 07:34

1 Answers1

2

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);
StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458