August 03, 2014 mismatched function return type inference of string and double | ||||
---|---|---|---|---|
| ||||
So I just started learning D this weekend, and I'm trying to understand why the following example will not work... Essentially what I am trying to do is cast the templated child stored in the parent container as the correct form, return some T value, and use auto to return the correct value type.. It seems from the errors I get regarding mismatched return type inference of string and double, that the compiler, for whatever reason, is assuming auto is a double? int main(string[] argv) { Parent[] Array; Array ~= new Child!(double)(3.0); Array ~= new Child!(string)("text"); foreach(item;Array) { auto val = value(item,item.type); //writeln(std.conv.to!string(value(item,item.type))); } return 0; } auto value(Parent item, int type) { if(item.type == 1) { return Fun!double(cast(Child!double)item); } else if(item.type==2) return Fun!string(cast(Child!string)item); else return 0; } auto Fun(T)(Child!T c) { return c.Value; } public class Parent { int type=-1; } public class Child(T) : Parent { T value; public this(T value) { this.value=value; SetType(); } private void SetType() { if(typeid(T) == typeid(int)) type=0; if(typeid(T) == typeid(double)) type=1; if(typeid(T) == typeid(string)) type=2; } @property public T Value(){return value;} } |
August 03, 2014 Re: mismatched function return type inference of string and double | ||||
---|---|---|---|---|
| ||||
Posted in reply to matt | On Sunday, 3 August 2014 at 22:01:23 UTC, matt wrote: > auto value(Parent item, int type) > { > if(item.type == 1) > { > return Fun!double(cast(Child!double)item); Here you're returning a double. > } > else if(item.type==2) > return Fun!string(cast(Child!string)item); Here you're returning a string. You're trying to return different, incompatible types depending on runtime data (`type`). That's not possible. The return type must be known at compile time. |
Copyright © 1999-2021 by the D Language Foundation