C ++ macros: parameter management (case study)

I need to replace

GET("any_name") 

with

 String str_any_name = getFunction("any_name"); 

The hard part is how to trim quotation marks. Possible? Any ideas?

+4
source share
3 answers

What about:

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

Or, to provide protection against problems with nested macros:

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

Using:

 SAFE_GET(foo) 

And this is what compiled:

 String str_foo = getFunction("foo"); 

Key points:

  • Use ## to combine macro parameters into one token (token => variable name, etc.)
  • And # for formatting a macro parameter (very useful when performing "reflection" in C / C ++)
  • Use the prefix for your macros since they are all in the same “namespace” and you don’t need collisions with any other code. (I chose MLV based on your username).
  • Wrapper macros help if you insert macros, i.e. call MLV_GET from another macro with different merge / line parameters (according to the comment below, thanks!).
+25
source

One approach is not to specify a name when invoking a 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 ); } 
+2
source

In answer to your question no, you cannot “cancel” quotes in C ++. But, as the other answers show, you can “add them”. Since you will still be working with a string literal (right?), You should be able to switch to the new method.

+2
source

All Articles