Make `& Class.foo` illegal

H. S. Teoh hsteoh at quickfur.ath.cx
Thu Aug 27 16:30:03 UTC 2020


On Thu, Aug 27, 2020 at 11:20:17AM +0000, Johan via Digitalmars-d wrote:
> Currently this code is not rejected by the compiler and instead
> creates non-functioning (undefined) code:
> ```
> struct S {
>     void foo() {}
> }
> 
> void main() {
>     auto a = &S.foo;
> }
> ```
> 
> See https://issues.dlang.org/show_bug.cgi?id=21195 .
> 
> Considering https://www.digitalmars.com/articles/b68.html, why not
> simply reject `&S.foo` during semantic analysis?
[...]

In C++, there's this construct called a member function pointer, which
has its own special type and requires the caller to specify an object
before the function can be called.  Arguably, that's what D should be
implementing.

If we have no intention of implementing member function pointers, then
this construct should indeed be illegal, or otherwise return void* so
that you cannot accidentally dereference it.

I thought about making it return a function pointer with S* as the first
parameter, but as Kinke pointed out in the bugnotes, the base object in
a method call is treated specially and cannot be generally assumed to be
the first argument to a function. So this will require a special
function pointer type, or be forced to void* so that comparisons work
but you can't actually call it. (Which TBH makes little sense; if we're
going to allow &S.foo at all, we should do it in a thorough way and
implement member function pointers properly, instead of doing a
half-assed job with void*.)


T

-- 
Never step over a puddle, always step around it. Chances are that whatever made it is still dripping.


More information about the Digitalmars-d mailing list