Fallback 'catch-all' template functions

Andrej Mitrovic via Digitalmars-d digitalmars-d at puremagic.com
Thu Sep 1 01:50:53 PDT 2016


On 9/1/16, Manu via Digitalmars-d <digitalmars-d at puremagic.com> wrote:
> So, consider a set of overloads:
>
>   void f(T)(T t) if(isSomething!T) {}
>   void f(T)(T t) if(isSomethingElse!T) {}
>   void f(T)(T t) {}
>

Best thing I can think of is to use a forwarding template:

-----
import std.stdio;

// forwarding (or dispatching) template
void f(T)(T t)
{
    static if(is(typeof( fImpl(t) )))  // found match
    {
        fImpl(t);
    }
    else  // no matches, use fallback
    {
        fallback(t);
    }
}

void fImpl(T)(T t) if (is(T == int)) { writefln("Int: %s", t); }
void fImpl(T)(T t) if (is(T == float)) { writefln("Float: %s", t); }
void fallback(T)(T t) { writefln("Generic: %s", t); }

void main ( )
{
    f(int(1));
    f(float(1.0));
    f("string");
}
-----


More information about the Digitalmars-d mailing list