C++ stream polymorphy on stack?
I would like to do something like this:
std::wistream input = std::wifstream(text);
if (!input) input = std::wistringstream(text);
// read from input
i.e. have text either interpreted as a filename, or, if no such file exists, use its contents instead of the file's co开发者_JS百科ntents.
I could of course use std::wistream * input
and then new
and delete
for the actual streams. But then, I would have to encapsulate all of this in a class (constructor and destructor, i.e. proper RAII for exception safety).
Is there another way of doing this on the stack?
You could abstract the logic that works with std::wistream& input
into a function of its own, and then call it with a std::wifstream
or std::wistringstream
as appropiate.
I could of course use std::wistream * input and then new and delete for the actual streams. But then, I would have to encapsulate all of this in a class (constructor and destructor, i.e. proper RAII for exception safety).
This is what std::unique_ptr
is for. Just use std::unique_ptr<std::istream>
.
Is there another way of doing this on the stack?
No way.
As the copy-assignment is disabled for all stream classes in C++, you cannot use it.That immediately implies that what you want is not possible.
Have you considered auto_ptr or unique_ptr to manage the wistream pointer?
http://www.cplusplus.com/reference/std/memory/auto_ptr/
精彩评论