lundi 27 février 2017

Append a string to a variable (function name) in #define MACRO

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.

Aucun commentaire:

Enregistrer un commentaire