infer type argument in classe constructor?

Edwin van Leeuwen via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Mar 29 03:32:19 PDT 2016


On Tuesday, 29 March 2016 at 10:13:28 UTC, Puming wrote:
> Hi,
>
> I'm writing a generic class:
>
> ```d
>
> struct Message { ... }
>
> class Decoder(MsgSrc) {
> }
> ```
>
> When using it, I'd have to include the type of its argument:
>
> ```
> void main() {
>    Message[] src = ...;
>
>    auto decoder = new Decoder!(Message[])(src);
>
>    ...
> }
> ```
>
> Can it be inferred so that I only need to write?
>
> ```d
> auto decoder = new Decoder(src); // you can infer the type from 
> src.
> ```

You can't directly. This is (AFAIK) because this()() can also be 
templated, making it impossible to just derive. The common way in 
D to deal with this/work around it is to create a helper function 
that can infer it:

```D
auto decoder(T)(T src)
{
   return new Decoder!T(src);
}

auto dec = decoder(src)
```

This pattern is widely used in phobos (e.g. tuple and Tuple)


More information about the Digitalmars-d-learn mailing list