逗号C / C ++宏 [英] Comma in C/C++ macro

查看:108
本文介绍了逗号C / C ++宏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有这样一个宏

#define FOO(type,name) type name

哪些我们可以使用像

Which we could use like

FOO(int, int_var);

但并不总是那样简单:

But not always as simple 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 as flexible. Plus type incompatibilities have to be dealt with. Any idea how to resolve this with macro ?

推荐答案

由于尖括号也可以重新present(或出现)比较操作符&LT; &GT; &LT; = &GT; = ,喜欢它的各种平衡支架确实宏扩展不能忽视尖括号内逗号() [] {} 。您可以在括号括起来的宏参数:

Because angle brackets can also represent (or occur in) the comparison operators <, >, <= and >=, macro expansion can't ignore commas inside angle brackets like it does with the various balanced brackets (), [] and {}. You can enclose the macro argument in parentheses:

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

问题是那么的参数保持宏观扩张,这prevents正从中读出在大多数情况下一个类型里面括号。

The problem is then that the parameter remains parenthesized inside the macro expansion, which prevents it being read as a type in most contexts.

一个好的技巧要解决这是在C ++中,你可以使用函数类型提取带括号的类型名称类型名:

A nice trick to workaround this is that in C++, you can extract a typename from a parenthesized type name using a function type:

template<typename T> struct argument_type;
template<typename T, typename U> struct argument_type<T(U)> { typedef U type; };
#define FOO(t,name) argument_type<void(t)>::type name
FOO((std::map<int, int>), map_var);

由于形成功能类型忽略额外的括号,就可以使用这个宏带或不带括号,其中类型名称不包含逗号:

Because forming function types ignores extra parentheses, you can use this macro with or without parentheses where the type name doesn't include a comma:

FOO((int), int_var);
FOO(int, int_var2);

在C,当然,这是因为类型的名称不能包含括号外的逗号是没有必要的。因此,对于跨语言的宏可以这样写:

In C, of course, this isn't necessary because type names can't contain commas outside parentheses. So, for a cross-language macro you can write:

#ifdef __cplusplus__
template<typename T> struct argument_type;
template<typename T, typename U> struct argument_type<T(U)> { typedef U type; };
#define FOO(t,name) argument_type<void(t)>::type name
#else
#define FOO(t,name) t name
#endif

这篇关于逗号C / C ++宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆