Problem with immutables and Template typeof(this)

anonymous via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Dec 28 14:21:20 PST 2014


On Sunday, 28 December 2014 at 22:07:31 UTC, AuoroP via
Digitalmars-d-learn wrote:
> I have been trying to figure templates out...
>
> template ExampleTemplate(T)
> {
>     struct ExampleTemplate
>     {
>         T value;
>
>         // constructor
>         auto this(T value)

Constructors don't have return types.

>         {
>             this.value = value;
>             return this;

Constructors don't return.

>         }
>
>         // opAdd
>         typeof(this) opAdd(typeof(this) that) // immutable
>         {
>             typeof(this) result;
>             result.value = this.value + that.value;
>             return result;
>         }
>     }
> }
>
> alias ExampleTemplate!int Example;
> immutable immutableEx = Example(1);
> Example ex = Example(1);
> Example ex2 = immutableEx + ex;
>
>
> I get this error with mutbale opAdd:
>
> example.d(27): Error: mutable method
> example.ExampleTemplate!int.ExampleTemplate.opAdd is not
> callable using a immutable object
>
>
> I get this error with immutable opAdd
> -------~-------+-------~-------=-------~-------+-------~-------
> example.d(18): Error: cannot modify immutable expression
> result.value
> example.d(27): Error: template instance
> example.ExampleTemplate!int error instantiating
>
>
> I get that typeof(this) is immutable ExampleTemplate!int.
> I can't find any way to cast immutable away because
> typeof(this) is the only way I know to get the type.

The type is ExampleTemplate, so:
              ExampleTemplate result;

But if you actually need to, you can use std.traits.Unqual to get
the unqualified version of a type:
              import std.traits: Unqual;
              Unqual!(typeof(this)) result;


More information about the Digitalmars-d-learn mailing list