Search code examples
d

Template in D programming


Can someone explain the code below? I get confused when I try to understand how isNumeric!T works in this case.

auto foo(T)(T n) if (isNumeric!T) {
     return (T m) {return m > n;};
}

void main() {
    auto hoo5 = foo!int(1000);
    writeln(hoo5(93));
    writeln(hoo5(23));
}

Solution

  • Start with:

    auto foo(T)(T n) if (isNumeric!T) {
         // ignore this for now
    }
    

    foo is a generic function that takes one argument of its generic type. if (isNumeric!T) is a compile-time check from std.traits that guarantees foo's type is numeric. Non-numeric types won't work. Its return type is inferred and in this case is a delegate.

    This:

    (T m) {return m > n;}; //returned from foo
    

    is a delegate literal (or closure). It's basically a function pointer with state. In this case, it closes over the parameter n passed to foo. In your example:

    auto hoo5 = foo!int(1000);
    

    is effectively translated to the function:

    bool hoo5 (int x) { return x > 1000; }
    

    So when you call hoo5, it returns a boolean indicating if its argument is greater than 1000 - but only in your specific case.

    If you call foo like this:

    auto hoo5 = foo!double(1.2345);
    

    You get a reference to a function that returns a boolean indicating if its argument (a double) is greater than 1.2345.