Boost logo

Boost :

From: Douglas Gregor (gregod_at_[hidden])
Date: 2001-06-09 10:29:00


On Saturday 09 June 2001 10:54 am, you wrote:
> The boost.function discussion got me thinking about how a class can support
> the
>
> if(f) {}
>
> syntax, without unwanted consequences. Here's what I came up with:
>
> #include <cstring>
>
> struct X
> {
> void f() {}
> };
>
> typedef void (X::*pmf)();
>
> struct F
> {
> operator pmf ()
> {
> return empty()? 0: &X::f;
> }
>
> bool empty()
> {
> return false;
> }
> };
>
> int main()
> {
> F f;
>
> if(f) {}
>
> f == f;
> f != f;
>
> // f - f;
> // f + 4;
> // f < f;
> // *f;
> // f[5];
> // std::memcpy(&f, f, 4);
> // delete f;
> }
>
> The commented lines do not compile. This leaves us only with operator==/!=
> to worry about.
>
> What do you think? :-)
>
> --
> Peter Dimov
> Multi Media Ltd.

Looks great! Operator== and != can be made useless with:
void operator==(const F&, const F&);
void operator!=(const F&, const F&);

If you try to use the result of ==/!=, you get a compiler error (no
conversion from void to bool/int/etc). The sample code gets a link-time error
because the sample code doesn't use the result of == or !=. Alternatively the
above operator definitions could be inline functions that do nothing, so a
statement like:
f==f;

is a no-op.

        Doug


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk