Templated ctors can't call each other?

Andrej Mitrovic andrej.mitrovich at gmail.com
Thu Sep 22 12:54:52 PDT 2011


import std.typetuple;
import std.traits;

struct Foo
{
    this(T1, T2)(T1 x, T2 y) if (allSatisfy!(isIntegral, T1, T2))
    {
        this.x = x;
        this.y = y;
    }

    this(P)(P point)  // ..constraints needed of course
    {
        this(point.x, point.y);
    }

    int x, y;
}

struct Point { int x, y; }
void main()
{
    auto foo = Foo(Point(1, 2));
}

test.d(14): Error: constructor call must be in a constructor
test.d(24): Error: template instance test.Foo.__ctor!(Point) error instantiating

It's only an issue with code reusability though. I could easily
populate the fields inside the ctor that takes a Point without calling
other ctors. Or I could create a special "ctor()" function and call
that from the templated ctors, e.g.:

struct Foo
{
    void ctor(T1, T2)(T1 x, T2 y) if (allSatisfy!(isIntegral, T1, T2))
    {
        this.x = x;
        this.y = y;
    }

    this(T1, T2)(T1 x, T2 y) if (allSatisfy!(isIntegral, T1, T2))
    {
        ctor(x, y);
    }

    this(P)(P point)  // ..constraints
    {
        ctor(x, y);
    }

    int x, y;
}

struct Point { int x, y; }
void main()
{
    auto foo = Foo(Point(1, 2));
}

So is the original code a rejects-valid bug or is this by design?


More information about the Digitalmars-d-learn mailing list