delegate, template and alias
Heromyth
bitworld at qq.com
Mon Dec 19 05:15:44 PST 2011
== Quote from Philippe Sigaud (philippe.sigaud at gmail.com)'s article
> 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);
> }
Thanks greatly. Your code makes me understanding D's template much more.
The template in D is so amazing.
> writeln("test called with void delegate(" ~
> AsynchronousActionParam!F ~ ").");
writeln("test called with void delegate(" ~
AsynchronousActionParam!F.stringof ~ ").");
> I suppose you do *not*want the commented line?
I want to convert a delegate type define in C# to D's, as such:
public delegate void AsynchronousAction<T>(T argument, AsyncContinuation asyncContinuation);
public static void ForEachItemSequentially<T>(IEnumerable<T> items, AsyncContinuation asyncContinuation, AsynchronousAction<T> action)
{
......
}
More information about the Digitalmars-d-learn
mailing list