www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - No polymorphism?

reply Dgame <r.schuett.1987 gmail.com> writes:
I may be just tired, but could somebody explain this behaviour to 
me? It seems odd to me:

----
interface I
{
}

class S : I
{
}

void test1(I[])
{
}

void test2(I)
{
}

void main()
{
	test1([new S()]); // Works
	test2(new S()); // Works
	
	I i = new S();
	test2(i); // Works
	
	S s = new S();
	test2(s); // Works
	
	I[] si = [new S()];
	test1(si); // Works
	
	S[] ss = [new S()];
	test1(ss); // Fails
}
----

Compiler output: test.d(32): Error: function test1 (I[] _param_0) 
is not callable using argument types (S[])

Why isn't the compiler able to deduce S[] => I[]? Or is it just 
me?
I've tried dmd 2.075
Jul 24 2017
next sibling parent reply Adam D. Ruppe <destructionator gmail.com> writes:
On Monday, 24 July 2017 at 17:29:55 UTC, Dgame wrote:
 	S[] ss = [new S()];
 	test1(ss); // Fails

 Why isn't the compiler able to deduce S[] => I[]? Or is it just 
 me?
This is exactly because of polymorphism. Consider the following: ``` S[] ss = [new S()]; I[] i = ss; // pass it to the function or whatever for implicit conversion class OtherDerived : I {} i[0] = new OtherDerived(); // looks OK, otherDerived is also interface I ``` But now, ss[0], the same array as i, no longer points to an S! You broke the type system.
Jul 24 2017
parent Dgame <r.schuett.1987 gmail.com> writes:
On Monday, 24 July 2017 at 17:33:48 UTC, Adam D. Ruppe wrote:
 On Monday, 24 July 2017 at 17:29:55 UTC, Dgame wrote:
 	S[] ss = [new S()];
 	test1(ss); // Fails

 Why isn't the compiler able to deduce S[] => I[]? Or is it 
 just me?
This is exactly because of polymorphism. Consider the following: ``` S[] ss = [new S()]; I[] i = ss; // pass it to the function or whatever for implicit conversion class OtherDerived : I {} i[0] = new OtherDerived(); // looks OK, otherDerived is also interface I ``` But now, ss[0], the same array as i, no longer points to an S! You broke the type system.
So, tired it is. Thanks a lot.
Jul 24 2017
prev sibling parent reply Steven Schveighoffer <schveiguy yahoo.com> writes:
On 7/24/17 1:29 PM, Dgame wrote:

 Why isn't the compiler able to deduce S[] => I[]? Or is it just me?
 I've tried dmd 2.075
I know you got the explanation already, but just in case you actually need to call something like test1 but only have an S[]: test1(ss.map!((I i) => i).array) -Steve
Jul 24 2017
parent Dgame <r.schuett.1987 gmail.com> writes:
On Monday, 24 July 2017 at 18:15:20 UTC, Steven Schveighoffer 
wrote:
 On 7/24/17 1:29 PM, Dgame wrote:

 Why isn't the compiler able to deduce S[] => I[]? Or is it 
 just me?
 I've tried dmd 2.075
I know you got the explanation already, but just in case you actually need to call something like test1 but only have an S[]: test1(ss.map!((I i) => i).array) -Steve
Thanks.
Jul 24 2017