Make `& Class.foo` illegal
Avrina
avrina12309412342 at gmail.com
Fri Aug 28 01:26:58 UTC 2020
On Friday, 28 August 2020 at 00:25:15 UTC, sarn wrote:
> On Thursday, 27 August 2020 at 16:30:03 UTC, H. S. Teoh wrote:
>> 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.
>
> I don't know if you've seen them before, but these two articles
> explain the reasoning behind D not having member function
> pointers:
> https://www.drdobbs.com/cpp/member-function-pointers-in-d/231600610
> https://www.codeproject.com/Articles/7150/Member-Function-Pointers-and-the-Fastest-Possible
>
> tl;dr: C++ member function pointers are complicated when you
> get into the details, and the sanest implementation is with
> thunks that are equivalent to lambdas or delegates.
> Ironically, the most common usage of member function pointers
> turned out to be building complicated versions of lambdas and
> closures (at least before C++ got them built in).
>
> None of that says anything about syntax, but it's why D doesn't
> have member function pointers, per se, like C++ does.
D does technically have them. They just aren't type safe. As
other people have said, the type should be either void*, or a
delegate with a null data pointer.
import std.stdio;
struct A {
float value;
void foo() { writeln(this); }
}
void main() {
void delegate() dg;
int a = 10;
dg.funcptr = &A.foo;
dg.ptr = &a; // no type safety, should be A*
dg(); // basically equivalent to C++'s member function pointer
}
With the example it makes sense why &A.foo would return a pointer
and not a delegate. But because there's no special type, it
incorrectly is of type `void function()` when it doesn't fit that
definition.
Yes it doesn't technically need member function pointers, but the
current implementation in D is broken (for many years) and not
type safe like C++.
More information about the Digitalmars-d
mailing list