Thread overview
How to overload with enum type?
Oct 15, 2017
Domain
Oct 15, 2017
Domain
Oct 15, 2017
Jonathan M Davis
October 15, 2017
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?
October 15, 2017
On Sunday, 15 October 2017 at 08:47:42 UTC, Domain 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 know I can do that with this:

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

But that looks strange.
October 15, 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