how to overload an operator to assert object as boolean value ? (not !())

K

Kai Wu

Hello,

Sometimes it is desired to assert an object as boolean value, e.g.

class A{
};
.......

A a;
while(a=next()){
.......
}

i have learnt that the operator !() could be overloaded to simulate the
bahaviour,
nevertheless in various situations it makes more sense to assert an object
directly
(like a pointer does), using !() make it a bit awkward ...

Br,Kai
 
S

sadhu

class Test
{
bool value;

public:

Test() : value(true)
{}

operator bool()
{
return value;
}
};

Be careful though, it might catch you unaware some times..

Regards
Senthil
 
I

Ivan Vecerina

sadhu said:
class Test
{
bool value;

public:

Test() : value(true)
{}

operator bool()
{
return value;
}
};
The danger with that is that suddenly the following
statements become valid as well:
Test t;
int a = t; // yes, bool can convert to an int...

A better way is replace the bool conversion with:
operator const volatile void* ()
{ return value ? this : 0; }
This still allows you to write if( t ) , but is
less prone to unexpected conversions.

Even safer is to provide a conversion to a member
function pointer type... but this gets a bit ugly IMHO.


For myself, I prefer to only implement the ! operator,
and to write if( !! t ) - because I normally use
the !! operator to make conversions to bool explicit.


Ivan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,045
Latest member
DRCM

Latest Threads

Top