I am trying to get a bool value out of user defined object.
For example with float or int I can do something like
float a = 3.5
if (a) doSomething();
I want my class to look like this:
class Socket {
...
...
};
...
Socket T;
if (!T) cout << "Error occured";
else {
doStuff();
}
Of course I can define a function that returns bool (like bool isValid();) and call it directly, but I would like to know if it is possible.
In C++11, you can safely convert your type to a boolean value:
If your compiler doesn’t support that, then you could write the same thing without
explicit; however, that can be a bit dangerous because it enables implicit conversions to any numeric type. Instead, you could use a hack known as the safe bool idiom:This returns a pointer type which can’t be converted into anything except
bool.