C++ Macros: manipulating a parameter (specific example)

岁酱吖の 提交于 2019-12-03 10:08:53

问题


I need to replace

GET("any_name")

with

String str_any_name = getFunction("any_name");

The hard part is how to trim off the quote marks. Possible? Any ideas?


回答1:


How about:

#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));

Usage:

SAFE_GET(foo)

And this is what is compiled:

String str_foo = getFunction("foo");

Key points:

  • 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!).



回答2:


One approach is not to quote the name when you call the macro:

#include <stdio.h>

#define GET( name ) \
    int int##name = getFunction( #name );   \


int getFunction( char * name ) {
    printf( "name is %s\n", name );
    return 42;
}

int main() {
    GET( foobar );
}



回答3:


In answer to your question, no, you can't "strip off" the quotes in C++. But as other answers demonstrate, you can "add them on." Since you will always be working with a string literal anyway (right?), you should be able to switch to the new method.



来源:https://stackoverflow.com/questions/806543/c-macros-manipulating-a-parameter-specific-example

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!