Is there C macro for member methods?
c, class, function-pointers, macros, methods
Solution
Yes, it is possible if you're able to use the variadic macros feature:
// ...
#define CALL_METHOD(x, y, ...) x->y(x, ##__VA_ARGS__)
struct string
{
char *value;
size_t (*size)(struct string *);
int (*compare)(struct string *, struct string *);
int (*set_value)(struct string *, const char *);
};
// ...
int main()
{
// ...
CALL_METHOD(s1, set_value, "foo");
CALL_METHOD(s2, set_value, "bar");
printf("s1->size(s1) = %zu;\n", s1->size(s1));
printf("CALL_METHOD(s1, size) = %zu;\n", CALL_METHOD(s1, size));
printf("s1->compare(s1, s2) = %d;\n", s1->compare(s1, s2));
printf("CALL_METHOD(s1, compare, s2) = %d;\n", CALL_METHOD(s1, compare, s2));
// ...
}
Problem
Functions can be coupled to their referring structure by using function pointers. ``` struct string { char *value; size_t (*size)(struct string *); }; size_t size(struct string *this) { size_t i; for(i = 0; this->value[i] != '\0'; ++i); return i; } struct string *construct() { string this = (string)malloc(sizeof(struct string)); this.size = &size; // ... } int main() { struct string *s = construct(); // ... s->size(s); // explicitly pass self reference } ``` But I would like to get rid of passing the `this` pointer manually. I know that this is done implicitly in C++ when you call a method of an object. Is there a way to create a macro for this in C that works for all methods and signatures? For example, I could think of a syntax like this. ``` s=>size(); // implicitly pass self reference ``` Please note that this is just for learning purpose. I know that it is better to just use C++ if that is possible and you'd like to use class coupling. But I'm interested of how it could be done in C.