How to overload with enum type?

Jonathan M Davis newsgroup.d at jmdavisprog.com
Sun Oct 15 09:17:28 UTC 2017


On Sunday, October 15, 2017 08:47:42 Domain via Digitalmars-d-learn wrote:
> void f(int i)
> {
>      writeln("i");
> }
>
> void f(E)(E e) if (is(E == enum))
> {
>      writeln("e");
> }
>
> enum E { A }
> E e = E.A;
> f(e);    // output i
>
> How can I overload with enum type?

I'd strongly advise against overloading a templated function with a
non-templated function. Basically, if you do that, it will always use the
non-templated function if it can and not bother with the templated function
unless the argument can't work with the non-templated one.

Really, if you're using a template constraint on one overload, use template
constraints on all overloads, or you're going to get some corner cases like
the one you hit which will cause you grief.

void f(T)(T t)
    if(is(T == int))
{
    writeln("i");
}

void f(T)(T t)
    if(is(T == enum))
{
    writeln("e");
}

or

void f(T)(T t)
    if(is(T == enum) || is(T == int))
{
    static if(is(T == enum))
        writeln("e");
    else
        writeln("i");
}

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list