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?
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)
.
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!
In C++ struct
is nothing but public class
. This is not the case in C.
精彩评论