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

后端 未结 3 2091
太阳男子
太阳男子 2021-02-04 19:34

I need to replace

GET(\"any_name\")

with

String str_any_name = getFunction(\"any_name\");

The hard part is ho

相关标签:
3条回答
  • 2021-02-04 20:11

    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 );
    }
    
    0 讨论(0)
  • 2021-02-04 20:25

    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!).
    0 讨论(0)
  • 2021-02-04 20:26

    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.

    0 讨论(0)
提交回复
热议问题