Why does this code only work with `std.conv.to` whilst not with `cast`?

thebluepandabear therealbluepandabear at protonmail.com
Sun Jan 8 12:39:37 UTC 2023


On Sunday, 8 January 2023 at 12:35:38 UTC, matheus wrote:
> On Sunday, 8 January 2023 at 11:29:10 UTC, thebluepandabear 
> wrote:
>> ...
>
> There is an explanation here: 
> https://forum.dlang.org/post/tqukutfzeaxedunuvkum@forum.dlang.org
>
> But in any case I'd like to point it out that I think you could 
> do that foreach without casting or std.conv by just omitting 
> the type of the variable you're iterating:
>
> import std.stdio, std.conv;
>
> interface IDog {
>     void bark();
> }
>
> class Dog: IDog{
>     string s;
>     this(string _s){s = _s;}
>     void bark(){writeln(s);}
> }
>
> class List{
>     IDog[] dogs;
>     void add(T)(T d){ dogs ~= d;  }
> }
>
> void main(){
>     auto d1 = new Dog("meaw!");
>     auto d2 = new Dog("wof!");
>     auto l = new List();
>     l.add(d1);
>     l.add(d2);
>
>     foreach(d; l.dogs){ // No type informed for "d"
>         d.bark();
>     }
> }
>
> Prints:
>
> meaw!
> wof!
>
> Matheus.

The `foreach` worked for that case since `bark` is a method of 
`IDog`. `update` is not so a conversion to `Button[]` is needed.

I will look at your resource, thanks.


More information about the Digitalmars-d-learn mailing list