Some of us who have the knack of writing metaprograms in D know that many algorithms can be implemented with both recursive templates and CTFE. A simple example is map:

Recursive template instantiation:

template staticMap(alias pred, A...)
{
    static if (A.length)
        alias TypeTuple!(pred!(A[0]), staticMap!(A[1..$])) staticMap;
}

CTFE:

template staticMap(alias pred, A)
{
    mixin("alias TypeTuple!(" ~ _staticMap(A.length) ~ ") staticMap;");
}

private string _staticMap(size_t len)
{
    string result;
    if (len)
    {
        result ~= "pred!(A[0])";
        for(size_t i = 1, i < len; ++i)
        {
            result ~= ", pred!(A[" ~ to!string(i) ~ "])";
        }
    }
    return result;
}

It is not easy to decide which approach to implement in a library because both have drawbacks.

Can anybody give informed advice as to which one is preferable in practice? Or should a library provide both?



Reply via email to