Purity, @safety, etc., in generic code

Steven Schveighoffer schveiguy at yahoo.com
Fri Feb 22 08:09:31 PST 2013


On Fri, 22 Feb 2013 10:04:23 -0500, deadalnix <deadalnix at gmail.com> wrote:

> On Thursday, 21 February 2013 at 14:17:16 UTC, Steven Schveighoffer  
> wrote:
>>>>> Explain me how the hell you overload on implicit parameter types ?
>>>>
>>>> A method is simply a function that takes a hidden parameter of an  
>>>> object or struct.
>>>>
>>>> Really, a method with a signature Obj.foo() is a function with a  
>>>> signature foo(Obj this)
>>>>
>>>> A const method Obj.foo() const is a function with a signature  
>>>> foo(const(Obj) this)
>>>>
>>>> So it's equivalent to saying you can overload:
>>>>
>>>> foo(int *x)
>>>> foo(const(int) *x)
>>>>
>>>> To disallow this would be unnecessarily restrictive.
>>>>
>>>
>>> That is called avoiding the question.
>>
>> I guess it's called not understanding the question?
>>
>
> The question is how do you overload function on the hidden parameter.  
> The answer, we both know it is that you can't.

I just demonstrated that you can.  Here it is spelled out:

class A {
    void foo() {}
    void foo() const {}
}

> You say that this is is just like a regular function but this is in fact  
> very different. You have virtual dispatch and overriding capabilities in  
> case of methods. And combined with the capability of overload on const,  
> this create a whole new set of problems.
>
> The principal one being :
>
> class A {
>      void foo() {}
> }
>
> class B {
>      override void foo() const {}
> }
>
> Add a const foo method to A, and B;foo don't overload the same method  
> anymore.

That's because you have changed the overload set, and this is a case of  
overriding with contravariance.

I can do the same trick without const:

class X {}
class Y : X {}

class A {
    void foo(Y y) {}
}

class B {
    override void foo(X x) {}
}

Now, add the function void foo(X x) into class A, and B.foo doesn't  
override the same function any more.

Note, this code doesn't compile, because contravariance is only allowed on  
the 'this' parameter.  Not sure why.

BTW, you are misusing overload to mean override (or specifically  
overriding with contravariance?), and I understand the mistake now, this  
is why I was confused on your original comment.

-Steve


More information about the Digitalmars-d mailing list