Can I pass a function by parameter?
Jakob Ovrum via Digitalmars-d
digitalmars-d at puremagic.com
Sun Sep 7 22:04:20 PDT 2014
On Monday, 8 September 2014 at 03:01:40 UTC, AsmMan wrote:
> I got it. Why it doesn't works if foo is a method?
Taking the address of a method/member function yields a delegate,
not a function pointer. Delegates are fat pointers; they contain
a pointer to the function as well as a pointer to the context
(the context is a hidden argument to the function, such as the
this-reference of a class method). The context pointer is needed
when calling the function, so they are encapsulated in one
convenient type, which is the delegate type.
Function pointers can be converted to delegates through a simple
wrapper function (which is how std.functional.toDelegate achieves
it), but delegates cannot be wrapped by a function pointer
without introducing additional parameters to the function in
order to pass the context pointer. Additionally, the *type* of
the context pointer is erased, which is immensely handy as it
means delegates with different contexts can be freely mixed, but
it means there's no way to know the type of the context (such as
a class type) just from the delegate, so there is no generic
`toFunctionPointer` function that would roughly do the inverse of
`toDelegate`. Each case has to be dealt with on a case-by-case
basis.
As function pointers can be converted to delegates, delegates are
the more versatile of the two. I recommend using delegates unless
there is a good reason not to.
More information about the Digitalmars-d
mailing list