TDPL: Operator Overloading

Steven Schveighoffer schveiguy at yahoo.com
Wed Aug 25 07:53:33 PDT 2010


On Tue, 24 Aug 2010 18:19:25 -0400, Andrej Mitrovic  
<andrej.mitrovich at whatever.com> wrote:

> What I don't understand is how the constructor can be called like that.  
> In my example the mixin would convert the code to:
>
> return CheckedInt(10);
>
> But if I ever tried a call like "CheckedInt(10)" in a unittest block, it  
> wouldn't work. So how does this magic work?

BTW, a unit test model I use in dcollections quite a bit is putting unit  
tests inside the template itself.  Then the unit test enjoys the same  
benefits.  e.g.:

struct CheckedInt(N) if(isIntegral!N)
{
    void foo(N n)
    {
      ...
    }

    unittest
    {
       CheckedInt ci;
       ci.foo(1);
    }
}

The only caveat is you have to instantiate the template to get the unit  
test to run :)  So on the bottom of your module you have to do this:

unittest
{
     CheckedInt!int ci1;
     CheckedInt!uint ci2;
     ...
}

The great benefit however is if you write your unit tests in a generic  
way, you can rigorously test your struct with all possible template  
instantiations without writing any extra code.  I've found the only limit  
here is generating data -- the literals have to match the N type.   
CheckedInt only instantiates if N is integral, but if that constraint  
wasn't there, then CheckedInt!string wouldn't compile because the unit  
test can't convert the literal 1 to a string.

-Steve


More information about the Digitalmars-d-learn mailing list