views:

474

answers:

3

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?

+8  A: 

How about:

#define GET(X) String str_##X = getFunction(#X);

GET(any_name)

## is a token merge operator. # stringizes a parameter.

Marcus Lindblom
One comment - using token pasting and stringizing operators should be done indirectly using function-like macros in order to prevent problems using them with macro parameters down the road. See: http://stackoverflow.com/questions/216875/in-macros/217181#217181
Michael Burr
Good point. I've seen the technique but I've never been bitten by it, cause I don't use nested macros that much.
Marcus Lindblom
+1  A: 

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 );
}
anon
+1  A: 

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.

j_random_hacker