Thread overview | ||||||
---|---|---|---|---|---|---|
|
October 12, 2017 Get and add to function body | ||||
---|---|---|---|---|
| ||||
Is there any way to get the function body of a function, delegate, and lambda? I'd also like to extend functions by "wrapping" them at compile time generically. For example, I'd like to get all the properties of a class and add some code to them(sort of like adding a scope, prolog, and/or epilog). Is any of this possible in D? |
October 12, 2017 Re: Get and add to function body | ||||
---|---|---|---|---|
| ||||
Posted in reply to Psychological Cleanup | I'd also like to be able to save and store delegates, functions, and lambdas. One can't store the pointer to the function because it will be invalid, so another means is required, any ideas? Save("f", (int){ ... }); // Saves to disk auto f = Load("f"); // Loads from disk f(3); |
October 12, 2017 Re: Get and add to function body | ||||
---|---|---|---|---|
| ||||
Posted in reply to Psychological Cleanup | On Thursday, October 12, 2017 23:33:39 Psychological Cleanup via Digitalmars-d-learn wrote:
> Is there any way to get the function body of a function, delegate, and lambda? I'd also like to extend functions by "wrapping" them at compile time generically. For example, I'd like to get all the properties of a class and add some code to them(sort of like adding a scope, prolog, and/or epilog).
>
> Is any of this possible in D?
You can introspect on symbols in D using __traits, std.traits, and is expressions, and that will allow you to get a function's signature, but it is not possible to get at the function's body. If you want to extend a function by wrapping it, you can certainly generate a wrapper, but that will mean generating a new function that calls the original and not doing anything with the code inside of the original function. You cannot alter existing code when generating code at compile time. You can just examine existing code and generate new code.
- Jonathan M Davis
|
October 13, 2017 Re: Get and add to function body | ||||
---|---|---|---|---|
| ||||
Posted in reply to Psychological Cleanup | On 10/12/17 7:33 PM, Psychological Cleanup wrote:
> Is there any way to get the function body of a function, delegate, and lambda? I'd also like to extend functions by "wrapping" them at compile time generically. For example, I'd like to get all the properties of a class and add some code to them(sort of like adding a scope, prolog, and/or epilog).
>
> Is any of this possible in D?
Something like this may work:
struct S(T)
{
private T obj;
auto ref opDispatch(string item, Args...)(auto ref Args args) {
prolog();
scope(exit) epilog();
mixin("return obj." ~ item ~ args.length == 0 ? ";" : "(args);");
}
}
Probably needs some more machinery to work for everything.
-Steve
|
Copyright © 1999-2021 by the D Language Foundation