[comp.lang.c++] "recursive" function prototype?

bvs@light.uucp (Bakul Shah) (05/07/88)

The following is not exactly what was asked for but it is the only way
in C of defining self-type returning functions _without_ using casts.

struct  state {
	struct state (*next)(struct state);
};

Example use:

state_machine(struct state initstate)
{
	struct state state = initstate;

	while (state.next)
		state = state.next(state);
}

The need for some extra syntactic sugar is unfortunate but (to my way of
thinking) preferable to use of ``casts'' or ``void (*)()''s.  Of course,
in practice you rarely want to use a function that returns another
function of the same type.
-- 
Bakul Shah

..!{ucbvax,sun}!amdcad!light!bvs

eppstein@garfield.columbia.edu (David Eppstein) (05/12/88)

sjs@spectral.ctt.bellcore.com (Stan Switzer):
> The lack of functions returning {functions returning}* can hardly be
> considered a serious flaw in C, but such functions ARE useful.

chris@mimsy.UUCP (Chris Torek):
> Agreed.  Traditionally, this has been done with ... [icky casts -- DE].

A cleaner approach is to wrap the function pointers in a recursive struct:

    struct foo;
    typedef foo (* foo_func)();
    struct foo {
	foo_func fn_ptr;
	foo(foo_func f) { fn_ptr = f; }
	foo operator()() { return (*fn_ptr)(); }
    };

    foo bar() { return bar; }
-- 
David Eppstein   eppstein@garfield.columbia.edu   Columbia U. Computer Science