On Monday, 20 March 2017 at 16:55:38 UTC, StarGrazer wrote:
typeof(&method) fails unless method is static. Says & requires
this.
But for typeof, it shouldn't matter and should pass.
So how to get a function pointer to a non static member
function(of an interface)?
One warning beforehand:
If the method is not static, a function pointer by itself is
useless, you should use a delegate; non-static methods have a
hidden this parameter (OOP), merely taking the address of such a
method (i.e. a function pointer) would leave you with something
you could not invoke, since you can't explicitly pass the hidden
this to a function pointer.
I've tried creating the type like
T t;
typeof(&t.method) fptr;
The correct syntax for the above would be either
typeof(&T.method) fptr;
or
typeof(t.method)* fptr;
, both of which declare fptr as a function pointer. You won't be
able to use fptr the way I think you expect, however:
fptr = &t.method;
will not work, because the RHS is a delegate (which uses the
address of t as the hidden this parameter implicitly) and the LHS
requires a function pointer.
For most cases, this is exactly what auto storage class is for:
auto fptr = &t.method;
If you need the type for another function's parameter's type,
then that won't work, of course. Two solutions I see there are
1) Make that function templatized
2) Create a template that can be used like this (you'll want to
consult std.traits for this):
void foo (delegateOf!(T.method) fptr) {}