Passing functions to functionals

Lars T. Kyllingstad public at kyllingen.NOSPAMnet
Tue Nov 30 03:59:57 PST 2010


In my library I have a lot of functionals (functions that take other 
functions as parameters).  Here is an example that shows the style I use 
to define them:

    // Example: Evaluate the function/delegate/functor f at x.
    auto eval(F, X)(F f, X x) { return f(x); }

    // Test
    void main()
    {
        int add2(int i) { return i + 2; }
        assert (eval(&add2, 1) == 3);
    }

In other words, the function is passed as a run-time parameter.  I've 
seen this (or similar) style used in Phobos, but there, I've also noted 
that functions are sometimes passed as template alias parameters:

    // Same as above, using template alias parameter.
    auto eval(alias f, X)(X x) { return f(x); }

    // Test
    void main()
    {
        int add2(int i) { return i + 2; }
        assert (eval!add2(1) == 3);
    }

I'd be grateful if people would share their knowledge of the pros and 
cons of each method.  For instance, are there any situations where 
template alias parameters don't work?


Thanks,

-Lars


More information about the Digitalmars-d-learn mailing list