C ++宏:操作参数(具体的例子) [英] C++ Macros: manipulating a parameter (specific example)
本文介绍了C ++宏:操作参数(具体的例子)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要更换
GET("any_name")
与
String str_any_name = getFunction("any_name");
难的是如何剪掉引号。可能?任何想法?
The hard part is how to trim off the quote marks. Possible? Any ideas?
推荐答案
如何
#define UNSAFE_GET(X) String str_##X = getFunction(#X);
或者,要对嵌套的宏观问题的安全防范:
Or, to safe guard against nested macro issues:
#define STRINGIFY2(x) #x
#define STRINGIFY(x) STRINGIFY2(x)
#define PASTE2(a, b) a##b
#define PASTE(a, b) PASTE2(a, b)
#define SAFE_GET(X) String PASTE(str_, X) = getFunction(STRINGIFY(X));
用法:
SAFE_GET(foo)
这是什么编译:
String str_foo = getFunction("foo");
要点:
- 使用##到宏观参数组合成一个标记(标记=>变量名称等)
- 和#为 (在C / C ++做反思的时候非常有用)字符串化宏参数
- 使用一个preFIX为您的宏,因为它们都是在同一个空间,你不想与任何其他code碰撞。 (我选择MLV根据您的用户名)
- 的包装宏帮助,如果你巢宏,即与其他合并/ stringized参数另一个宏调用MLV_GET(按照下面的评论,谢谢!)。
- Use ## to combine macro parameters into a single token (token => variable name, etc)
- And # to stringify a macro parameter (very useful when doing "reflection" in C/C++)
- Use a prefix for your macros, since they are all in the same "namespace" and you don't want collisions with any other code. (I chose MLV based on your user name)
- The wrapper macros help if you nest macros, i.e. call MLV_GET from another macro with other merged/stringized parameters (as per the comment below, thanks!).
这篇关于C ++宏:操作参数(具体的例子)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文