Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top