Why can't I have overloading and generics?

Jonathan M Davis jmdavisProg at gmx.com
Fri Mar 9 19:38:24 PST 2012


On Friday, March 09, 2012 21:32:35 Caligo wrote:
>     struct B { }
>     struct C { }
>     struct D { }
> 
>     struct A {
> 
>       ref A foo(B item) {
>         /* do something special. */
>         return this;
>       }
> 
>       ref A foo(T)(T item) if(is(T == C) || is(T == D)) {
>         /* nothing special, do the same for C and D. */
>         return this;
>       }
>     }
> 
> Is this unreasonable?  iirc, C++ supports this, but not D.  What's the
> reason? Bug?
> 
> What's a good solution to this?
> 
> 1. a generic `foo()` that uses `static if`s?
> 
> 2. overload `foo()`, even if it means having function bodies that are
> exactly same (code duplication).?
> 
> 3. mixin templates?  I don't know about this because TDPL says it's
> experimental, and I've tried and I get weird errors.

It's a bug:

http://d.puremagic.com/issues/show_bug.cgi?id=1528

As a workaround, just add empty parens to the non-templated function to make 
it a templated function.

ref A foo()(B item) {}

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list