Comma in C/C++ macro

2019-01-02 17:40发布

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 ?

7条回答
旧时光的记忆
2楼-- · 2019-01-02 18:32

This is possible with P99:

#include "p99/p99.h"
#define FOO(...) P99_ALLBUTLAST(__VA_ARGS__) P99_LAST(__VA_ARGS__)
FOO()

The code above effectively strips only the last comma in the argument list. Check with clang -E (P99 requires a C99 compiler).

查看更多
登录 后发表回答