Can I conditionally replace preprocessor arguments?

When working with the unit test framework, I came across a situation in which I would like to test the macros. Simply put, I would like to extend the macro FOO(x) so that FOO(int) short and FOO(anything_else) long .

With C ++ templates, of course, this is not a problem. But here I need a real token replacement, not just a typedef . That is, FOO(char) FOO(char) i; must be a valid definition equal to long long i; .

+6
source share
2 answers

As far as I know, the only string-like operations available in C macros are inserting / concatenating tokens (using ## ) and building them using # ).

I am sure that the closest thing you are going to receive includes listing of such possibilities:

 #define FOO(x) FOO__##x #define FOO__int short #define FOO__short long #define FOO__long long #define FOO__char long // ... for each type you want to replace 

Inspiration from this question .

+3
source

what you are trying to do is impossible.

Macros are evaluated by the c preprocessor, which as the name implies execution before the compiler runs. He does not know what types of your characters are not yet.

Why don't you create a class for the type that throws itself into the right position when the compiler calculates it.

0
source

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


All Articles