Variadic macros: expanding inserted tokens

I wonder if variation macros can be "nested". I am really concerned about GCC and Clang. My macro definition is as follows:

/**
 * @brief Invoke an instance method.
 */
#define $(obj, method, ...) \
    ({ \
        typeof(obj) _obj = obj; \
        _obj->interface->method(_obj, ## __VA_ARGS__); \
    })

I use this to conveniently call instance methods in my OO structure ( https://github.com/jdolan/objectively ):

$(array, addObject, obj);

The boss is working. Unfortunately, I have not yet figured out a way to resolve the nesting of these calls, which would be very useful in some situations; eg:.

/**
 * @see MutableSetInterface::addObjectsFromArray(MutableSet *, const Array *)
 */
static void addObjectsFromArray(MutableSet *self, const Array *array) {

    if (array) {
        for (size_t i = 0; i < array->count; i++) {
            $(self, addObject, $(array, objectAtIndex, i));
        }
    }
}

Nested macro calls above will not compile because the internal call never expands. Can this be fixed, or have I already abused the preprocessor outside it? :)

+3
1

. ; tl; dr , . , :

#define MI(obj, method, ...) \
  ({ \
    typeof(obj) _obj = obj; \
    _obj->interface->method(_obj, ## __VA_ARGS__); \
  })

#define M(obj, method, ...) MI(obj, method, __VA_ARGS__)

// This will now expand properly.
M(self, addObject, M(array, objectAtIndex, M(foo, bar, i)))

: , $ C; , , .

+6

Source: https://habr.com/ru/post/1680777/


All Articles