I'm at time examining streams. I wonder of what type streams are. Essentially I thought if I intstantiate a stream, e.g. with std::ifstream ifs(my_file.txt); it would be an object. But how then it's been able testing if the stream is good or not (if (!ifs) handle error)? If this is able, the stream must return an int or bool type. But then, why its not being able determinig the type of a stream?
Here I have a piece of code that don't compile:
1 2 3 4 5 6 7 8 9 10 11
#include <iostream>
#include <sstream>
int main()
{
std::string str = "dump";
std::stringstream sstr(str);
sstr >> str;
std::cout << (sstr); // should return a value > 0, but doesn't compile;
}
then the stream get evaluated. Why don't work the evaluation the first program? And, genarally, how do grasp an object of a stream and not the evaluation to built in type?
Streams have an explicit conversion operator to bool which makes the stream objects implicitly convertible to bool in some situations where a bool is expected. It also overloads the ! operator.
Thank you Peter, this operator was new for me. But it's sparse documented how operator bool() functions would be implemented, so I tested this by my own. For the sake of completeness, if somewhere would look at this thread, here the implementation. operator bool() takes no args and has no return type, but needs a return statement.