Guelque Hadrien
Guelque Hadrien

Reputation: 47

Use a macro to call a function from a string

I have a series of functions that I need to call, and all the calls are of the form:

StartingFunctionName[Thing]Callback(&[Thing]);

Where [Thing] is the same thing each time for example, I have to call

StartingFunctionNameMyFunctionCallback(&MyFunction);

and I'd like to rather do foo(MyFunction); where foo would be the macro.

I was wondering if there was a way to use a macro, so that its input is the string (or something like that) Thing, and the output is the correct line of code.

Upvotes: 1

Views: 507

Answers (2)

Guelque Hadrien
Guelque Hadrien

Reputation: 47

The answer was to use the ## #define foo(thing) StartingFunctionName##thing(& thing)

Upvotes: 1

If this is your pattern:

StartingFunctionName[Thing]Callback(&[Thing]);

and you want the token 'Thing' replaced, then via function like macro:

#define foo(Thing) \
    StartingFunctionName##Thing##Callback(&Thing)

Example:

foo(exit);

expands to

StartingFunctionNameexitCallback(&exit);

Upvotes: 2

Related Questions