Comma in C/C++ macro

PoP picture PoP · Dec 12, 2012 · Viewed 39.8k times · Source

Say we have a macro like this

#define FOO(type,name) type name

Which we could use like

FOO(int, int_var);

But not always as simply as that:

FOO(std::map<int, int>, map_var); // error: macro "FOO" passed 3 arguments, but takes just 2

Of course we could do:

 typedef std::map<int, int> map_int_int_t;
 FOO(map_int_int_t, map_var); // OK

which is not very ergonomic. Plus type incompatibilities have to be dealt with. Any idea how to resolve this with macro ?

Answer

not-a-user picture not-a-user · Nov 7, 2013

If you can't use parentheses and you don't like Mike's SINGLE_ARG solution, just define a COMMA:

#define COMMA ,

FOO(std::map<int COMMA int>, map_var);

This also helps if you want to stringify some of the macro arguments, as in

#include <cstdio>
#include <map>
#include <typeinfo>

#define STRV(...) #__VA_ARGS__
#define COMMA ,
#define FOO(type, bar) bar(STRV(type) \
    " has typeid name \"%s\"", typeid(type).name())

int main()
{
    FOO(std::map<int COMMA int>, std::printf);
}

which prints std::map<int , int> has typeid name "St3mapIiiSt4lessIiESaISt4pairIKiiEEE".