I tried to understand the statement:
int main() {
fstream inf( \"ex.txt\", ios::in );
char c;
while( inf >> c ) {
What does ( inf >> c ) return in the while loop above?
void*
. The loop test resolves to while (inf.operator void*() != NULL)
.
How does a reference can be evaluated as true or false?
But supporting conversion to bool or something convertible to bool.
How does the internal implementation of istream actually work?
It just returns a reference to itself (return *this
) so it can support chaining.
To return a self ref you just return *this
. You don't actually declare an internal self reference. You can have reference members, but you must initialize them in the constructor initializer list: class Foo { Foo(int& some_int_ref) :my_ref_member(some_int_ref)
istream has another overload to determine its boolean value.
Example of a chainable member (like operator >>
, but in this case just an ordinary function) and giving a class a boolean value (although the latter is a complex subject worthy of its own subject):
#include <iostream>
class X {
bool B;
public:
X() :B(false) { }
X& toggle() { B = !B; return *this; }
operator void*() { return B ? this : 0; }
};
int main()
{
X x;
x.toggle().toggle().toggle();
if (x)
std::cout << "true!" << std::endl;
}
EDIT: I didn't want to delve into operator bool
vs operator void *
in this answer, but this old stackoverflow question should give you good references: Why is "operator bool()" invoked when I cast to "long"?