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

matheus matheus at gmail.com
Sun Jan 8 12:35:38 UTC 2023


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.


More information about the Digitalmars-d-learn mailing list