TDPL: Operator Overloading

Andrej Mitrovic andrej.mitrovich at gmail.com
Wed Aug 25 07:01:31 PDT 2010


Ok I think I am kind of getting this. The template name inside a template is it's instantiation. I can do "CheckedInt.variable" and get back the value of "variable" in the current instantiation.

The trouble is, when you do a call like CheckedInt() you will loose all other data that you had before:

module binary_ops;

import std.stdio : writeln;
import std.traits;
import std.exception;

unittest
{
    auto foo = CheckedInt!(int)(5);
    auto bar = CheckedInt!(int)(5);
    foo.x = 4;
    bar.x = 5;

    foo = foo + bar;
    
    writeln(foo.x);     // writes 0
    writeln(bar.x);     // writes 5
}

void main() { }

struct CheckedInt(N) if (isIntegral!N)
{
    private N value;
    int x;
    
    this(N value)
    {
        this.value = value;
    }

    // addition
    CheckedInt opBinary(string op)(CheckedInt rhs) if (op == "+")
    {
        auto result = value + rhs.value;
        
        enforce(rhs.value >= 0 ? result >= value : result < value);
        return CheckedInt(result);
    }
}

Here I've lost the value of x. "return CheckedInt(result);" calls the constructor of the already instantiated template, but because of the way D works (afaik) it first has to deconstruct the object before constructing it again. And that includes initializing all members to their .init value before calling the constructor.

So, I don't like that return statement at all..

Steven Schveighoffer Wrote:

> On Tue, 24 Aug 2010 18:43:49 -0400, Andrej Mitrovic  
> <andrej.mitrovich at whatever.com> wrote:
> 
> 
> > I wasn't refering to the mixin, but the call to CheckedInt(). mixin  
> > compiles "value" ~ op ~ "rhs.value", which in this case evaluates to 5 +  
> > 5 and the whole call becomes CheckedInt(10).
> >
> > What I don't understand is how you can construct a new CheckedInt struct  
> > by calling it with CheckedInt(10), when I have to use a call like  
> > CheckedInt!(int)(10) outside the struct (in main or in a unittest block).
> 
> Inside a template instantiation, the template name without template  
> parameters is equivalent to the current instantiation.
> 
> It saves a lot of typing.
> 
> -Steve



More information about the Digitalmars-d-learn mailing list