6

Working with a unit test framework, I came across a situation in which I'd like to test macro arguments. Simply said, I'd like to expand the macro FOO(x) such that FOO(int) would be short and FOO(anything_else) would be long.

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

Brian Tompsett - 汤莱恩
  • 5,438
  • 68
  • 55
  • 126
MSalters
  • 167,472
  • 9
  • 150
  • 334

2 Answers2

3

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

I'm pretty sure the closest you're going to get involves enumerating the possibilities like so:

#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.

Community
  • 1
  • 1
vergenzt
  • 8,943
  • 4
  • 34
  • 44
0

what you are trying to do is impossible.

Macros are evaluated by the c preprocessor, which as the name implies runs before the compiler runs. It doesn't know what the types of your symbols are yet.

Why don't you create a class for the type that casts itself to the right thing at the time it is evaluated by the compiler.

Rafael Baptista
  • 10,771
  • 4
  • 37
  • 58
  • I don't care about types. I know that `int` at the preprocessing stage is just a token. Still, I want to act conditionally on the token `int`. – MSalters Jun 21 '12 at 08:43