3

I would like to change a function that displays some info about the class so that can print to the screen or write to a file depending on the kind of stream I am passing to the function.

I would like to have a function like:

void output(int x, default (what class do I need here??) &stream=cout){
    stream << x ;
}  

What is the proper way to do that??? Thanks for the help!

lucacerone
  • 9,859
  • 13
  • 52
  • 80
  • This is a question I asked that is quite possibly a duplicate, at least in terms of passing an `ostream` to a function with the ability to choose which you like when calling the function. http://stackoverflow.com/questions/10356300/is-it-possible-to-pass-cout-or-fout-to-a-function – ChiefTwoPencils Aug 06 '12 at 03:30

1 Answers1

3

You generally want std::ostream&. Note that most programmers would just overload operator<< rather than define a separate output() function like you've done.

chrisaycock
  • 36,470
  • 14
  • 88
  • 125
  • Thanks for the help chrisaycock. I define an output function because it takes in input other variables that I need to write certain things to disk :) I just kept the example minimal! – lucacerone Aug 06 '12 at 10:04
  • I'm sorry, but it dosn't work if I write: void output(default std::ostream& os=std::cout) I get some syntax error message. How would yout write that? – lucacerone Aug 06 '12 at 10:15
  • Some generic syntax error.. I rewrote the function from scratch and it worked though.. must have been some silly typo... – lucacerone Aug 06 '12 at 14:08
  • I don't think the keyword ``default`` in ``void output(default std::ostream& os=std::cout)`` is valid. To overload a function by providing a default value for an argument, just add `` = value``, no ``default`` is needed. – Colin D Bennett Dec 20 '13 at 17:36