Comma in C/C++ macro(C/C++ 宏中的逗号)
问题描述
假设我们有一个像这样的宏
Say we have a macro like this
#define FOO(type,name) type name
我们可以像这样使用
FOO(int, int_var);
但并不总是那么简单:
FOO(std::map<int, int>, map_var); // error: macro "FOO" passed 3 arguments, but takes just 2
当然可以:
typedef std::map<int, int> map_int_int_t;
FOO(map_int_int_t, map_var); // OK
这不是很符合人体工程学.必须处理 Plus 类型的不兼容性.知道如何用宏解决这个问题吗?
which is not very ergonomic. Plus type incompatibilities have to be dealt with. Any idea how to resolve this with macro ?
推荐答案
因为尖括号也可以表示(或出现在)比较运算符<
、>
, <=
和 >=
,宏扩展不能像在括号中那样忽略尖括号内的逗号.(这也是方括号和大括号的问题,即使它们通常作为平衡对出现.)您可以将宏参数括在括号中:
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 within parentheses. (This is also a problem for square brackets and braces, even though those usually occur as balanced pairs.) You can enclose the macro argument in parentheses:
FOO((std::map<int, int>), map_var);
问题在于,参数在宏扩展内仍然用括号括起来,这会阻止它在大多数情况下被读取为类型.
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++ 宏中的逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C/C++ 宏中的逗号
基础教程推荐
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01