0

Is it possible to append a string to a variable (function/field name) in MACRO? How?

#include <iostream>
using namespace std;

#define T1(hoho) \
   void hoho(){}

#define T2(hoho) \
   void hoho_(){}  //append underscore

T1(happy)
T2(sad)

int main() {
    happy(); //<--- work OK
    sad_();  //<--- this function not exist (compile error)
    return 0;
}

I want to use it for some (hacky-but-cool) function generation, e.g. :-

#define T3(hoho) \
int hoho_;  \
void hoho_clear(){hoho_=0;}  \
int hoho_get(){return hoho_;}  

class Magic{
    T3(magicField)    //<-- use only 1 MACRO parameter
};

The result will be like :-

class Magic{
    int magicField_;
    void magicField_clear(){magicField_=0;}
    int magicField_get(){return magicField_;}
};

I know it is not a good practice. I will rarely use it, I promise.

javaLover
  • 6,347
  • 2
  • 22
  • 67
  • Use `##`. http://stackoverflow.com/questions/2025858/what-does-mean-for-the-cc-preprocessor – kennytm Feb 28 '17 at 04:26
  • @kennytm Thank a lot!!! It works. Should I delete this question? I am so happy I got answer. I never know such feature exists. XD – javaLover Feb 28 '17 at 04:28
  • @kennytm Is it possible that what come after `##` is a variable that was defined somewhere else? `#define B C .... #define T1(A) A##B` I can't get it work, guess that it is impossible? – javaLover Feb 28 '17 at 04:35
  • Nevermind, I found it. http://stackoverflow.com/questions/1489932/how-to-concatenate-twice-with-the-c-preprocessor-and-expand-a-macro-as-in-arg Thank. – javaLover Feb 28 '17 at 04:43
  • [You should **not** delete the question](http://meta.stackexchange.com/questions/32311/do-not-delete-good-duplicates). – kennytm Feb 28 '17 at 05:12
  • @kennytm Yes, sir! I will **not** delete it. – javaLover Feb 28 '17 at 05:13

0 Answers0