delegate, template and alias

Philippe Sigaud philippe.sigaud at gmail.com
Sun Dec 18 13:04:58 PST 2011


On Sun, Dec 18, 2011 at 14:13, Heromyth <bitworld at qq.com> wrote:
> I have a delegate as a parameter in a function which is a template function.
> And I want to use alias for the delegate parameter.
> Is there a better way for this?

I suppose you do *not*want the commented line?

You can extract a template parameter with an is() expression. But the
extracted type is only accessible inside a static if.
Solution: expose it through an alias:

template AsynchronousActionParam(T)
{
    static if (is(T t == void delegate(U), U))
	alias U AsynchronousActionParam ;
    else
	static assert(false, "Bad AsynchronousActionParam call: " ~  T.stringof);
}

class TestC
{
    int b = 3;

    void test(F)(F func ) if (is(AsynchronousActionParam!F))
    {
        static if (is(AsynchronousActionParam!F == string))
	    func("It's me");
        else
            writeln("test called with void delegate(" ~
AsynchronousActionParam!F ~ ").");
    }

    this(int x)
    {
        b = x;
    }
}

void main()
{
    auto c = new TestC(3);

    void foo(string s) { writeln("foo: ", s);}

    c.test(&foo);
}


More information about the Digitalmars-d-learn mailing list