I'm generating some compile-time code. I need to append a suffix to a generated function name, based on a macro boolean. The suffix is either present or empty. How to do that?
#define FUNC_NAME(name, hasSuffix) name ## MAYBE_SHOW_SUFFIX(hasSuffix)
FUNC_NAME(foo, true); // would generate: foo_
FUNC_NAME(foo, false); // would generate: foo
Use the fact that the result of a macro expansion is expanded again:
#define WITHSUFFIX_true(name) name ## _
#define WITHSUFFIX_false(name) name
#define FUNC_NAME(name, hasSuffix) WITHSUFFIX_ ## hasSuffix(name)
FUNC_NAME(foo, true); // would generate: foo_
FUNC_NAME(foo, false); // would generate: foo
Result
foo_;
foo;
https://godbolt.org/z/EEM938jx9
Note that this only works because it expands the macro WITHSUFFIX_true or WITHSUFFIX_false given the condition true or false exactly. It won't work for other values like 1 or !0 or similar.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With