On Sunday, 13 January 2013 at 16:39:22 UTC, bearophile wrote:
Maxim Fomin:
dmd allows to call static functions on instance.
I think that's a D design mistake (and I think Jonathan Davis
agrees with me), but Walter prefers the current behavour.
I'll have to disagree and it should remain an error.
Consider his example, if it were allowed and you do:
Gun gun;
Gun.bar();
gun.bar();
What would happen? The first would call the static and the
second would call the non-static. Overloading-wise their
signatures are identical (static doesn't count). The difference
in the calls is a single letter and can easily go under the
radar; Without an actual difference in the signature it would be
easy to confuse the two. Now had one required an input then they
couldn't be messed up.
Let's go with a slightly more confounding example.
struct S {
int x;
int opIndex(int i){return i;}
//non-instance is always 0
static int length() {return 0;}
int length() const {return x;}
}
Assuming a function should call this (Say a foreach? once
there's more methods?), which is the correct length to call? If
the static is preferred then length is always 0, if non-static is
preferred (although slimmer) the length of 0 being returned by
accident is always there. If the static length is private, then
inside the struct S you always have to reference 'this.length' vs
'S.length' to keep them separate just to be sure.
I recall reading somewhere that in Java that technically calling
a static function by a instance was an error but instead only
gave you a warning; Kinda makes sense since methods affect it's
instance but static functions don't have an instance to work
with; They were more for functions that needed to be free but
couldn't due to the strict 'everything is an object' setup.