C++ Macros: manipulating a parameter (specific exa

2019-03-14 02:24发布

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?

3条回答
看我几分像从前
2楼-- · 2019-03-14 02:27

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楼-- · 2019-03-14 02:39

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!).
查看更多
看我几分像从前
4楼-- · 2019-03-14 02:46

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.

查看更多
登录 后发表回答