Purity, @safety, etc., in generic code

Steven Schveighoffer schveiguy at yahoo.com
Sat Feb 23 07:16:14 PST 2013


On Sat, 23 Feb 2013 01:06:43 -0500, deadalnix <deadalnix at gmail.com> wrote:

> On Friday, 22 February 2013 at 18:55:58 UTC, kenji hara wrote:
>> No, const/inout overload does not intend to solve 'method hiding'  
>> problem.
>>
>> To clarify the situation, I try to explain.
>>
>> class A {
>>   void foo() {}
>>   void foo() const {}
>> }
>>
>
> You missed the important part. I'm talking about overload, not override.  
> IE, not method hiding.
>
> What you have in class A here is useful for use cases that are now  
> solved by inout (getting ranges/iterator from collection for instance).

This actually is impossible to do with inout, unless your ranges are  
pointers or arrays (believe me, I tried with dcollections).  But that is  
not inout's fault, it's because we have no way to specify tail-const  
arbitrary types.

The above example does not work with inout, inout only makes sense on a  
method that returns something.  If you aren't returning anything, use  
const.

Here is something that inout cannot do:

class A {
    void foo() {writeln("mutable instance used!");}
    void foo() const {}
}

Remember, inout is only valid if ALL implementations (const, immutable,  
mutable) are identical.

And of course, if you want to count ALL overload possibilities, you can  
easily come up with more mainstream examples:

class A {
    private int _x;
    @property int x() const {return _x;}
    @property void x(int newx) {_x = x;}
}

So your special compiler rule, that makes extra work for the compiler  
maintainers, has to allow this case.  It's not a simple exception to add,  
and it adds pretty much no value.

If you don't want to provide overloads based solely on const, then don't.   
But it doesn't HURT for it to be allowed to compile.

I can also write this valid function:

void foo() {}

What is the point?  Yes, we can make the compiler refuse to compile this,  
but it will always inline to a noop, so it doesn't hurt to allow it to  
comiple.  And there is nothing in the grammar that disallows this.

D should not be dictating design, just syntax.  Design patterns are not  
something that I think a language should require.  At it's core, a const  
method is just another function with a const parameter.  To make special  
rules based on that seems overly invasive.

-Steve


More information about the Digitalmars-d mailing list