reference to 'self' inside a function
Rob T
rob at ucora.com
Mon Sep 24 22:07:09 PDT 2012
This is a little insane, but it works.
int Recurse(int a)
{
if (a <= 1)
return 1;
else
// can we replace explicit call to "Recurse"
// with "self" using a mixin or some other means?
// return a * Recurse(a - 1);
mixin("return a * mixin(__traits(identifier,
__traits(parent, {})))(a - 1);");
}
--rt
On Tuesday, 25 September 2012 at 04:42:43 UTC, Rob T wrote:
> On Sunday, 23 September 2012 at 17:15:13 UTC, Ben Davis wrote:
>> Here's another one that might work, and be less error-prone:
>>
>> mixin template Self() {
>> auto self = __traits(identifier, __traits(parent, {}));
>> }
>>
>> void test() {
>> mixin Self;
>> writeln(self);
>> }
>>
>
> OK, we've managed to get the calling function symbol name
> without re-specifying it. Now I wonder if we can perform mixin
> magic to execute a function recursively without re-specifying
> the function name?
>
> Example recursive function
>
> int Recurse(int a)
> {
> if (a <= 1)
> return 1;
> else
> // can we replace explicit call to "Recurse"
> // with "self" using a mixin or some other means?
> return a * Recurse(a - 1);
> }
>
>
> We could try and get the function pointer, but that seems like
> the wrong approach. I'd rather get the function name, do some
> mixin magic with it to generate the compile time code that uses
> the function name directly. Can we mixin a mixin???
>
> --rt
More information about the Digitalmars-d
mailing list