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

15,525

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

Solution 2

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.

Share:
15,525
Maleev
Author by

Maleev

Updated on June 22, 2022

Comments

  • Maleev
    Maleev almost 2 years

    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?