Delegate returning itself
Jonathan Marler via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Mon Dec 8 10:31:27 PST 2014
On Monday, 8 December 2014 at 14:38:37 UTC, Marc Schütz wrote:
> On Monday, 8 December 2014 at 14:31:53 UTC, Jonathan Marler
> wrote:
>> On Monday, 8 December 2014 at 14:08:33 UTC, Jonathan Marler
>> wrote:
>>> On Saturday, 6 December 2014 at 15:46:16 UTC, Adam D. Ruppe
>>> wrote:
>>>> The problem is the recursive *alias* rather than the
>>>> delegate. Just don't use the alias name inside itself so like
>>>>
>>>> alias MyDelegate = void delegate() delegate();
>>>>
>>>> will work. The first void delegate() is the return value of
>>>> the MyDelegate type.
>>>
>>> Yes I tried that as well. It still doesn't solve the issue.
>>> The delegate being returned doesn't return a delegate, it
>>> returns the "void" type. You would need to write delegate()
>>> delegate() delegate() delegate() ...FOREVER. I can't figure
>>> out a way to write this in the language even though the
>>> machine code it generates should be quite trivial.
>>
>> I did some digging and realized that C/C++ have the same
>> problem.
>> I found a nice post on it with 2 potential solutions
>> (http://c-faq.com/decl/recurfuncp.html). I liked the second
>> solution so I wrote up an example in D. If anyone has any
>> other ideas or can think of a way to improve my example feel
>> free to post and let me know, thanks.import std.stdio;
>>
>> struct StateFunc
>> {
>> StateFunc function() func;
>> }
>> StateFunc state1()
>> {
>> writeln("state1");
>> return StateFunc(&state2);
>> }
>> StateFunc state2()
>> {
>> writeln("state2");
>> return StateFunc(&state3);
>> }
>> StateFunc state3()
>> {
>> writeln("state3");
>> return StateFunc(null);
>> }
>> void main(string[] args)
>> {
>> StateFunc state = StateFunc(&state1);
>>
>> while(state.func != null) {
>> state = state.func();
>> }
>> }
>
> Nice! Using alias this, you can call the struct directly:
>
> struct StateFunc
> {
> StateFunc function() func;
> alias func this;
> }
> state = state();
>
> Now there still needs to be a way to just `return &state2;`
> instead of `return StateFunc(&state2);`...
Nice addition! I can't think of a way to solve the implicit
conversion from function pointer to struct, but not a big deal.
I'm mostly glad I found a way to do this with no overhead and no
awkward casting. Adding the implicit conversion would be icing
on the cake.
More information about the Digitalmars-d-learn
mailing list