Erik Wikström
11/22/2008 9:00:00 AM
On 2008-11-22 08:26, Paavo Helde wrote:
> "jason.cipriani@gmail.com" <jason.cipriani@gmail.com> kirjutas:
>
>> If I have:
>>
>> class Something {
>> public:
>> bool operator ! () const;
>> };
>>
>> Then I can do:
>>
>> Something s(...);
>> if (!s) ...;
>>
>> My question is, what operator do I need to overload if I want to be
>> able to define the behavior of this instead:
>>
>> Something s(...);
>> if (s) ...; // <-- notice no !
>
>
> The common approach is to use
>
> operator const void* () const;
>
> Now you can write:
>
> if (s) ...
> if (!s) ...
>
> This should return NULL for 'false' and a non-NULL valid pointer (like
> 'this') for 'true'. The problem with returning a bool is that it converts
> to numeric types too easily and can create hidden errors. Yes, this seems
> like a hack, but it's a widely used one.
I'm wondering if the new explicit conversion functions will solve this.
The standard says:
A conversion function may be explicit, in which case it is only
considered as a user-defined conversion for direct-initialization.
Since there is no initialisation going on in "if (s)", I suppose that we
will still have to use the "operator void*" hack.
--
Erik Wikström