Display inputs to std::ostream - c++

Disclaimer: I am a complete C++ beginner, and if there is a similar answer to this question, please direct me to it, as I may have missed it, not knowing much in the way of theory.
Suppose I have a method which accepts a reference to an ostream:
printAllObjects(std::ostream& os);
I am assuming it makes changes to the ostream, so that one can print the list of all of the objects to a file, say. (I might be wrong here)
Is there any way of seeing what it writes to the ostream? (via cout preferably)?

std::cout is an std::ostream, so just pass std::cout to the function and you'll see what it does:
printAllObjects(std::cout);
This flexibility is the very purpose of accepting a reference to std::ostream!
Other stream types1 inheriting from the std::ostream base include:
std::ofstream (for file output)
std::ostringstream (for string output).
1 That's not to say that std::cout is a type; it's not. It's a special, global instance of std::ostream.

Related

Two questions about cin and cout

Creating my own cin & cout is somewhat pointless, so I just curious about how.
I know that cin and cout are instances of istream/ostream class; however, I've tried some declarations like "std::istream mycin"
but didn't work.
Besides, I read a lot of posts saying that cin and cout are global variables, but we have to access them through std::cin or std::cout. My understanding is that global variables are those declared in the global scope, but cin and cout are obviously in the std namespaces. Which part of my knowledge is wrong? Thanks.
std::cin and std::cout are not just "instances of istream/ostream class". They are also connected to the C++ program's standard input and output stream.
How that happens, how that's done, is not specified by the C++ standard. Your C++ compiler and library does whatever needs to be done to make that happen, and the exact details of the underlying working is implementation defined. Merely declaring two std::istream and std::ostream objects of your own won't, of course, accomplish that by fiat. If you're interested, you can do some research and investigation, and determine how your C++ implementation or library goes about doing this, and reimplement it yourself, with your own instance of std::istream and std::ostream.
std::istream and std::ostream, by themselves, merely implement formatted input and output extraction operations using an underlying instance of a std::streambuf. std::istream and std::ostream's constructor takes a pointer to an instance of a std::streambuf that's used as the underlying input/output source/sink.
So, to summarize, in order to reimplement what std::cin and std::cout does, yourself, it is necessary to:
Implement a subclass of std::streambuf that handles the underlying input and output by using your operating system-specific resources to read or write to your terminal.
Use your std::streambuf subclass to construct an instance of a std::istream and/or std::ostream.

Adapter for std streams

I have an abstract class in my project, its derivatives is used for input/output to different locations.
It has virtual methods read and write.
virtual unsigned read(void *buf, unsigned len) = 0;
virtual void write(const void *buf, unsigned len) = 0;
I need a kind of an adapter between std streams (std::istream and std::ostream) and this class to redirect input/output to these methods.
So, for example, if
mystream << "some output";
is called, it will call the write method.
I guess i should overload std::istream and std::ostream or std::streambuf, but not sure which methods.
What is the better way to implement this?
There are lots of simple but not flexible ways of doing it. Most of these solution will not leverage istream or ostream. For instance, overloading the << operator is one way. The drawback is that you will have to implement this operator for all the usual types, and for all the standard manipulators, and so on. It may become a great burden.
This is sad because the whole thing about istream and ostream is only to parse and format not to do input or output. The I/O responsibility is given to the streambuf. And your task calls for a custom implementation of streambuf which uses your read and write methods.
The discussion is too long for such a small format as a stackoverflow answer but you can find good pointers in the following references.
References
http://www.mr-edd.co.uk/blog/beginners_guide_streambuf
http://en.cppreference.com/w/cpp/io/basic_streambuf
http://www.amazon.com/Standard-Library-Tutorial-Reference-2nd/dp/0321623215/ref=sr_1_1?ie=UTF8&qid=1442329302&sr=8-1&keywords=josuttis , this book contains a chapter dedicated to streambuf implementation.
Note
As advised, using boost.iostreams maybe a good fit, but I don't know it enough.
You might want to take a look at the boost iostreams library. It provides a framework that makes it easier to define iostreams with custom sources and sinks (input and output devices).
I am a fan of std::stringstream, and perhaps your class could make use of it.
std::stringstream ss;
ss << "some output";
from which something would invoke write like:
write(ss.str().c_str(), ss.str().size());
You will have to figure out how to connect the two, but this has the advantage of providing all stream io.
On the other hand, directly implementing operator << and >> is not too difficult.
I guess i should overload std::istream and std::ostream or
std::streambuf, but not sure which methods.
Start with the method you need first, then add functionality as you identify the requirements.

Should I create a temporary ostream using another's streambuf?

Suppose I have a function that takes an ostream & parameter o and writes to that ostream. An operator << implementation would be a good example.
ostream& operator << (ostream& o, const MyThing& t)
{
// ... interesting code here ...
return o;
}
Within the function, I might want to specify formatting options on the stream. For example, I might want a number to be printed as hex, no matter how the o is configured when it is passed in to the function.
Secondly, I might want to be able to make assumptions about the current formatting flags. For example, it would be nice to be able to assume that numbers were formatted as decimal unless I request otherwise.
Finally, by the time the function exits I want the formatting options on o to be the same as they were before the function was called, so as to appear unchanged to the caller. This is simply a matter of politeness to the caller.
Up until now I have achieved this by creating a local ostringstream within the function, doing all my work on that (including setting formatting options), and sending the .str() to o at the end of the function. The StackOverflow question here suggests that people cleverer than me take the same approach. However, it bothers me that I'm keeping so much data in ostringstreams that could perhaps be sent to the output earlier (the strings can get quite large).
I have two questions:
1) Is it legal, idiomatic, good form, etc. to create a temporary (stack based) ostream around o.rdbuf() and do my work on that ostream? My own tests and the page at cppreference.com appears to suggest that I can.
ostream& operator << (ostream& o_, const MyThing& t)
{
ostream o (o_.rdbuf());
// write stuff to "o",
// setting formatting options as I go.
return o_; // Formatting on the parameter ostream o_ unchanged.
}
2) Is there another, better way that I have not considered?
Boost IO State Savers are built exactly for this purpose.
That's not a bad solution; it's certainly legal. I don't think
it's too common, so it's probably a good idea to comment as to
why you're doing it.
The most frequent solution I've seen here is to create a state
saver class, which will save all of the state you need
(typically, flags(), precision() and fill()) in the
constructor, and restore it in the destructor, and then to
forceably set all of the options you want. (It may be possible
to use copyfmt for this, although this also copies things like
the exception mask, which you probably don't want to play with.)
The settings can be stored in a type of object called a fmtflags object, defined in a class called ios, which is included with iostream. You can declare one of
these objects, but you have to declare it using the scope resolution operator.
The following statement will save certain aspects of the format state in the variable old_settings:
ios::fmtflags old_settings = cout.flags();
Then, after doing the output using the new setting, you can restore the old setting by calling the same function with the old settings as an argument:
cout.flags(old_settings);
Other settings can be obtained and restored with member functions. For example,
int old_precision = cout.precision();
will save the current precision specification. Then
cout.precision(old_precision);
will restore the precision to the original value

Parameter of type "has << operator"

I need to draw my object on an out stream, which is usually cout.
But I also want the user to be able to input any stream that has << operator (such as QTextStream), so it doesn't have to be cout every time.
What's the easiest way to define such parameter?
So this is what I'd like to have, something compilable tho:
virtual void draw(GeneralOutStream out = std::cout)
{
out << m_name << std::endl;
}
I know I could use templates, (which is what I'm doing atm.) but I was hoping there would be a solution that doesn't require templates.
However, the template solution works fine, so basically I'm just curious.
I can think of Four approaches.
First, take std::ostream as your GeneralOutStream, and assume everyone inherits from it. Maybe write some stuff that wraps a QTextStream up in a way that makes it a std::ostream.
Second, write a template method that takes GeneralOutStream&& out and operates on it. This requires exposing your implementation in your header. I'd recommend this one. Quite strongly, but it does mean that virtual ends up being pretty useless.
Third, write a type erasure GeneralOutStream that exposes the parts of the general out stream you want to interact with within your class with a template constructor that stores the passed in generic type in a pImpl with virtual methods, then use that type within the implementation of your object. This has runtime overhead and is quite tricky to write, and resembles the pattern of std::function -- except GeneralOutStream has to handle being able to write an entire myriad of types!
If I was to write #3, GeneralOutStream would be a template that takes a sequence of types the GeneralOutStream is supposed to handle, then does some metaprogramming to expose exactly those overloads to <<. This gets really tricky, because you need to replicate overload resolution manually.
Forth, create an enumeration of "GeneralOutStream" types that you want to support. Use double-dispatch techniques to ferry references to instances of those types through a virtual method call, unbundling them at the other side and calling your implentation template methods, requiring that the implementing class handle the entire enumeration. This one is slightly less tricky to implement than #3, limits what types you can pass to the draw method, but allows full access to the type in the implementation class.
You want a solution any stream (derived from std::ostream) or for any object that has << operator?
In the first case, you can pass a reference to the stream object:
virtual void draw(std::ostream& out = cout) {
out << m_name << std::endl;
}
Passing a copy won't compile.
In the second case, the main problem is the interface, since it looks you want to define that function as virtual member. If is not the case and you still want a solution for any object (not necessary standard ostream, but any with operator << defined), you'll have to use templates.

How Best to Keep Function From Closing File?

So, I've been trying to be more rigorous with making any passed parameters that shouldn't be touched by a function const.
One situation I've encountered in some of my C++ code is the case where the object may change, but where I want to "lock out" functions from access certain key functionality of the object. For example, for an std::ifstream file handle, I may wish to prevent the function from closing the file.
If I pass it as a const &, the const part keeps me from performing standard file i/o, it seems.
e.g. I want something along the lines of
void GetTags(Arr<std::string> & tags, std::ifstream const& fileHandle)
...but written in such a way to allow file i/o but not open/close operations.
Is there any good/reliable way to do this in C++? What would be considered best practice?
This has already been done for you by the standard library design: Pass a reference to the base class std::istream instead, which does not have a notion of opening or closing - it exposes only the stream interface.
void stream_me(std::istream & is);
std::ifstream is("myfile.txt");
stream_me(is);
In your place I'd just pass a std::istream instead.
You could wrap the ifstream in an object that only exposed the functionality that you wished the caller to be able to use.
However, if you have a bunch of different functions, each with a different subset of ifstream's functionality, you'll end up with lots of different wrapper classes; so I don't see this as a general solution.
I think the best way would be to wrap the ifstream in a new class which only has member functions corresponding to the functionality you wantGetTags to have access to. Then pass that not the ifstream as the second argument to GetTags.