Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a C factory function?

Tags:

c

I have a struct that takes a function pointer, like this:

typedef int (*node_transition_func)( wint_t );

typedef struct lex_dfa_arc_t {

    node_transition_func func;
    int expected_return_val;
    struct lex_dfa_node_t * node;

} LEX_DFA_ARC_T;

And now I want to create a function that returns a function of the prototype "int func( wint_c );" For example:

node_transition_func input_equals( wint_t input, wint_t desired ) { ... }

Is it possible in C to have the function above actually work? I'm trying to avoid having to define a function for each letter (e.g. input_equals_letter_a, input_equals_letter_b, input_equals_letter_c, etc).

My other approach would be to just have the node_transition_func take in a wint_t and a wchar_t* of desired characters, but I was curious if my first approach would work.

Thanks!

like image 827
Scott Avatar asked Feb 26 '23 14:02

Scott


1 Answers

You could basically emulate closures & currying by instead of "returning a function" you return a struct that has the function pointer plus the bound variables. With a couple of #defines it may even look halfway sane.

OTOH, when you use a particular language, you should stick to its idioms. Closures are not the strong point of C. I suggest that you don't try to be overly generic in C code, if in doubt just use a switch(){}.

like image 175
edgar.holleis Avatar answered Feb 28 '23 05:02

edgar.holleis