开发者

C++ stream polymorphy on stack?

开发者 https://www.devze.com 2023-04-10 04:05 出处:网络
I would like to do something like this: std::wistream input = std::wifstream(text); if (!input) input = std::wistringstream(text);

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/

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号