Is it possible to change the behavior of if()
so that:
class Foo {
int x;
};
Foo foo;
if(foo)
only proceeds if the value of <
You can define an operator to convert the object to bool
class Foo
{
int x;
public:
operator bool() const
{
return x > 0;
}
};
But this can have unintended consequences because of implicit conversions to bool
when you don't desire the conversion to take place. For instance
int x = 42 + Foo();
C++11 solves this problem by allowing you to declare the conversion operator as explicit
, which then only allows implicit conversions in certain contexts, such as within an if
statement.
explicit operator bool() const // allowed in C++11
Now
int x = 42 + Foo(); // error, no implicit conversion to bool
int x = 42 + static_cast(Foo()); // OK, explicit conversion is allowed