On 12/28/2014 02:07 PM, AuoroP via Digitalmars-d-learn wrote:

> I have been trying to figure templates out...

Although the question has already been answered, here is a solution that combines most of the suggestions that have already been made. It does not need any kind of casting:

/* Eponymous template syntax is lighter */
struct ExampleTemplate(T)
{
    T value;

    this(T value)
    {
        this.value = value;
    }

    /* 1) As a shorthand, the name of the template is the same
     *    thing as this specific instantiation of it. For
     *    example, if the template is instantiated with "int",
     *    then ExampleTemplate alone means
     *    ExampleTemplate!int.
     *
     * 2) opAdd is marked 'const' so that it can work on
     *    mutable, const, and immutable objects.
     *
     * 3) The parameter is by-copy so that it can take rvalues as well.
     */
    ExampleTemplate opAdd(const(ExampleTemplate) that) const
    {
        return ExampleTemplate(this.value + that.value);

        /* Alternatively:

           auto result = ExampleTemplate(this.value + that.value);
           return result;
        */
    }
}

void main()
{
    /* New alias syntax makes more sense */
    alias Example = ExampleTemplate!int;

    immutable immutableEx = Example(1);
    Example ex = Example(1);
    Example ex2 = immutableEx + ex + immutableEx;
}

Ali

Reply via email to