digitalmars.D.learn - No polymorphism?
- Dgame (38/38) Jul 24 2017 I may be just tired, but could somebody explain this behaviour to
- Adam D. Ruppe (12/16) Jul 24 2017 This is exactly because of polymorphism. Consider the following:
- Dgame (2/19) Jul 24 2017 So, tired it is. Thanks a lot.
- Steven Schveighoffer (5/7) Jul 24 2017 I know you got the explanation already, but just in case you actually
- Dgame (3/11) Jul 24 2017 Thanks.
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
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
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:So, tired it is. Thanks a lot.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
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.075I 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
On Monday, 24 July 2017 at 18:15:20 UTC, Steven Schveighoffer wrote:On 7/24/17 1:29 PM, Dgame wrote:Thanks.Why isn't the compiler able to deduce S[] => I[]? Or is it just me? I've tried dmd 2.075I 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