On 03/10/2012 04:32 AM, 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.


I don't know what the best solution is. But the following works.



import std.stdio;


    struct B { }
    struct C { }
    struct D { }

    struct A {

      ref A foo(T)(T item) if (is(T==B)) {
        /* do something special. */
                                writeln("B");
        return this;
      }

      ref A foo(T)(T item) if(is(T == C) || is(T == D)) {
        /* nothing special, do the same for C and D. */
                                writeln("C or D");
        return this;
      }
    }


int main()
{
        A a;
        B b;
        C c;
        a.foo(b);
        a.foo(c);
        writeln("Test");
        return 0;
}

-----------------------output

B
C or D
Test

Reply via email to