scry
scry

Reputation: 1257

Struct parameter deduction in D

Just wondering why this does not compile. I thought the compiler could infer types for a parameterized struct?

void main() {
    auto arr = Arr([1,2,3]);
}

struct Arr(T) {
    private T[] data;
}

Error:

junk.d(25): Error: struct junk.Arr(T) is not a function template
junk.d(25): Error: struct junk.Arr(T) cannot deduce template function from argument types !()(int[])

Upvotes: 3

Views: 161

Answers (1)

jA_cOp
jA_cOp

Reputation: 3305

Code of the form:

auto arr = Arr([1,2,3]);

is a call to the constructor of Arr when Arr is a struct. In this case, there is no explicit constructor. If there was, it could have been templated, and parameter inference does work for templated constructors. Since there is no constructor, the parameters will be used to initialize the fields of Arr in the order they are declared. But, of course, Arr is a template, so the type to construct is not yet known.

If you think there should be parameter inference for this case, consider the following:

struct Arr(T)
{
    static if(is(T == bool))
        BitArray data;
    else
        T[] data;
}

In the above example, the types (and it could be the order too) of the fields are not known until the template is instantiated... so how would it infer?

The template has to be explicitly instantiated:

auto arr = Arr!int([1, 2, 3]);

Upvotes: 8

Related Questions