tags:

views:

163

answers:

4

Can I have functors in C? I mean for example in C++ I can do:

struct Rules
{

    operator()(/*maybe some args*/)
    {
    }
};

Some (fictitious) algorithm:

int sort(iter beg, iter end, Rules);

Can I do identically in C?

+7  A: 

Not identically, no. C doesn't support member functions for structures, nor operator overloading.

You can, however, pass and store function pointers. You could make your sort take a structure with a comparison function pointer, and call the passed function. For an example, see qsort in the C standard library...

qsort(void *base, size_t nel, size_t width, int (*compar)(const void *, const void *));

that last parameter is a sorting comparison function pointer. You could create a structure such as...

struct Rules_t
{
  int (*comparisonRule)(const void *, const void *);
} Rules;

then pass instances of this structure around calling, e.g. myRules->comparisonRule(a, b).

Adam Wright
This doesn't emulate the ability of functors to have state.
Oli Charlesworth
Not directly, no. As I said, C doesn't support functions. However, you can, in the same structure, have state. You will need to pass the structure instance to the function being called.
Adam Wright
A: 

No. In C you can do f() if and only if f is the name of a function or f is a pointer to a function.

You can't do it if f is a struct or any other kind of value.

sepp2k
A: 

In C++ struct is nothing but public class. This is not the case in C.

kuriouscoder
+2  A: 

Not really. At best, you could do something like:

int sort(iter a, iter b, bool (*cmp)(iter a, iter b, void *), void *p_state)
{
    ...
    cmp(a, b, p_state);
}


bool func(iter a, iter b, void *p_state)
{
    type_t *p_type = (type_t *)p_state;
    ...
}


type_t state;
...
sort(a, b, func, &state);

This allows you to give the function state, albeit manually.

You may be able to hide some of the clunkiness behind macros, but beware macros!

Oli Charlesworth