Reputation: 60381
I have a class that contains an std::ofstream
and an std::ifstream
(only one can be activated at a time). I would like to overload the operator()
to return the current active stream. But what is the common base type of std::ofstream
and std::ifstream
to return a common reference ?
Upvotes: 1
Views: 1194
Reputation: 45444
I would like to overload the operator() to return the current active stream This makes absolutely no sense and smells like a design flaw. Why do you want to return that? What should the caller of that operator be able to do with return value? It can neither do input nor output.
I dunno what you really want to do, but perhaps something like this could work for you, though it's dangerous
template<typename T> class wrapper
{
T*const ptr;
wrapper(T*p) : ptr(p) {}
public:
bool empty() const { return ptr; }
operator T& () const
{
if(empty()) throw some_exception("trying to use empty wrapper");
return *ptr;
}
friend some_class;
};
class some_class
{
ifstream _ifstream;
ofstream _ofstream;
bool ifstream_is_active;
bool ofstream_is_active;
public:
operator wrapper<ifstream> () const
{ wrapper<ifstream>(ifstream_is_active? &_ifstream : 0); }
operator wrapper<ofstream> () const
{ wrapper<ofstream>(ofstream_is_active? &_ofstream : 0); }
};
but this is dangerous, as you are potentially dealing with dangling pointers. You can avoid that by using shared_ptr
(work this out yourself), but that means that some_class
has no longer control over the lifetime of these streams.
Upvotes: 2
Reputation: 473537
Input and output streams are very different types. The only common base class they share is std::ios
. And that doesn't have much in it besides some error checking stuff.
The two stream types only share the most basic of interfaces. They have little to do with one another, for obvious reasons.
Upvotes: 1