Thin delegate adapter

Guilherme Vieira n2.nitrogen at gmail.com
Wed Jan 12 04:42:53 PST 2011


On Wed, Jan 12, 2011 at 10:41 AM, Guilherme Vieira <n2.nitrogen at gmail.com>wrote:

> Hi,
>
> I'm wondering if a delegate adapter template like isn't handy for Phobos
> (it may be especially useful for std.signal):
>
> class Switch
> {
>     enum State { ON, OFF }
>
>     void trigger()
>     {
>         switch (mState)
>         {
>             case State.ON: mState = State.OFF; break;
>             case State.OFF: mState = State.ON; break;
>             default: break;
>         }
>
>         if (watch !is null) watch(mState);
>     }
>
>     void delegate(State s) watch;
>
>     private State mState;
> }
>
> class ToggleButton
> {
>     @property toggled(bool toggled)
>     {
>         writeln("ToggleButton.toggled(", toggled, ")");
>     }
> }
>
> void main()
> {
>     scope s = new Switch();
>     scope b = new ToggleButton();
>
>     s.watch = &b.toggled; // error: invalid conversion
>     s.watch = adapt!("obj.toggled = cast(bool)(a)", Switch.State)(b);
>
>     s.trigger(); // prints `ToggleButton.toggled(true)`
>     s.trigger(); // prints `ToggleButton.toggled(false)`
>     s.trigger(); // prints `ToggleButton.toggled(true)`
>     s.trigger(); // prints `ToggleButton.toggled(false)`
> }
>
>
> Yes, it urges to be polished. Particularly, it doesn't support multiple
> arguments. I also wanted to place the argument type tuple somwhere else
> (actually wanted to hide it completely, but I think that's not possible).
>
> Feedback?
>
> --
> Atenciosamente / Sincerely,
> Guilherme ("n2liquid") Vieira
>

Oops, missed the template itself:

template adapt(alias fun, Arg)
{
    auto adapt(Object)(Object obj)
    {
        auto adaptImpl = new AdaptImpl!(fun, Object)(obj);
        return &adaptImpl.opCall!(Arg);
    }
}

class AdaptImpl(alias fun, Object)
{
    this(Object obj) { this.obj = obj; }
    auto opCall(Arg)(Arg a) { return binaryFun!(fun, "a", "obj")(a, obj); }

    private Object obj;
}


-- 
Atenciosamente / Sincerely,
Guilherme ("n2liquid") Vieira
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d/attachments/20110112/9e689fea/attachment.html>


More information about the Digitalmars-d mailing list