Amit
Amit

Reputation: 7818

Creating a function in c++ to output to designated source

I want to have a function that outputs certain pieces of information to a specific designated source that is inputted to the function. In code, what I mean is:

function output( source ) {

source << "hello" << endl;

}

where source can be a ofstream or cout. So that I can call this function like so:

output(cout) or ofstream otp ("hello"); output(otp)

My question is, how do I characterize source to make this work? It's fair to assume that source will always be a member of the std class

Thanks!

Upvotes: 4

Views: 123

Answers (5)

Robᵩ
Robᵩ

Reputation: 168646

function output( source ) {
  source << "hello" << endl;
}

If this is a member function, the point of which is to dump data about objects of the class of which it is a member, consider renaming it to operator<<. So, instead of

class Room {
  ...
  // usage myRoom.output(otp)
  void output(std::ostream& stream) {
    stream << "[" << m_name << ", " << m_age << "]";
  }
};

rather, try this:

class Room {
  ...
  // usage opt << myRoom << "\n"
  friend std::ostream& operator<<(std::ostream& stream, const Room& room) {
    return stream << "[" << room.m_name << ", " << room.m_age << "]";
  }
};

That way, you can display the state of your class using a more natural syntax:

std::cout << "My Room: " << myRoom << "\n";

instead of the klunky

std::cout << "My Room: ";
myRoom.output(std::cout);
std::cout << "\n";

Upvotes: 1

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361492

Write your function as:

std::ostream& output(std::ostream& source )
{
  return source << "hello" << endl;
}

Then you can use it as:

output(cout);

//and 
ofstream otp ("hello"); 
output(otp);

//and
output(output(cout));
output(output(output(cout)));
output(output(output(output(cout))));

//and even this:
output(output(output(output(cout)))) << "weird syntax" << "yes it is" ;

By the way, if the output function has many lines, then you can write it as:

std::ostream& output(std::ostream& source )
{
  source << "hello" << endl;
  source << "world" << endl;
  //....
  return source;
}

The point is that it should return source. In the earlier version, the function returns source.

Upvotes: 4

m0skit0
m0skit0

Reputation: 25873

IMHO, redirecting output should be done at the user level. Write your C++ like this:

cout << "hello" << endl;

And when executing the application, user can redirect the output to whatever he wants, say a file:

myapp > myfile

Upvotes: 0

You should pass an std::ostream& as argument

Upvotes: 1

Bill Lynch
Bill Lynch

Reputation: 81936

void output(std::ostream &source) {
    source << "hello" << std::endl;
}

or even:

template <T>
void output(T &source) {
    source << "hello" << std::endl;
}

Upvotes: 7

Related Questions