I have defined a class that's meant to represent a data series, which has an index and a set of values. Sometimes the user wants to specify a particular index of custom type, other times they don't care and we want to default to an array of contiguous "int" starting from 0.

I have attempted to create a class where the index type is a parameter, but defaults to int. I also tried to create two constructors: one for if the index values are not specified (in which the constructor makes the array of ints); and one where the user passes in a literal of values that match the specified type.

However, it seems that only the first constructor is getting called, even though I am passing in two parameters instead of one. Why isn't the call matching the second constructor and behaving as intended?


 import std.stdio;

 class MyClass(T, U = int) {

    T[] values;
    U[] index;

    this(T[] values) {
        this.values = values;
        // Default index of contiguous ints
        for (int i; i < values.length; i++) {
            index ~= i;
        }
    }

    this(T[] values, U[] index) {
        this.values = values;
        this.index = index;
    }
}

void main() {
    auto myc1 = new MyClass!(int)([1,2,-3]);

auto myc2 = new MyClass!(int, string)([1,2,-3], ["a", "b", "c"]); // Error: cannot append type int to type string[]

}

Reply via email to