mismatched function return type inference of string and double

matt via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Aug 3 15:01:22 PDT 2014


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;}
}


More information about the Digitalmars-d-learn mailing list