function overrides but is not covariant

Ali Çehreli acehreli at yahoo.com
Mon Apr 29 07:16:54 PDT 2013


On 04/28/2013 12:45 PM, Namespace wrote:

 > That surprised me a bit. Is that expected?
 >
 > ----
 > import std.stdio;
 >
 > struct A { }
 >
 > interface IFoo {
 >      void bar(ref const A);
 > }
 >
 > class Foo : IFoo {
 >      void bar(ref const A a) {
 >
 >      }
 >
 >      void bar(const A a) {
 >          return this.bar(a);
 >      }
 > }
 > ----
 > prints:
 >
 > Error: function c517.Foo.bar of type void(const(A) a) overrides but is
 > not covariant with c517.IFoo.bar of type void(ref const(A))

As others have said, one would expect this to compile because it is very 
common to overload on the same struct type, one taking by-value, the 
other taking by-reference. The former is mainly to capture rvalue struct 
objects and the latter is for lvalues.

To match what is common in Phobos and TDPL is to define the by-value 
overload without 'const':

     void bar(A a) {
         return this.bar(a);
     }

This example now compiles.

Ali



More information about the Digitalmars-d-learn mailing list