How to generate random variable names in C++ using macros?

前端 未结 8 2017
别跟我提以往
别跟我提以往 2020-12-01 07:56

I\'m creating a macro in C++ that declares a variable and assigns some value to it. Depending on how the macro is used, the second occurrence of the macro can override the v

相关标签:
8条回答
  • 2020-12-01 08:54

    Try the following:

    // This is some crazy magic that helps produce __BASE__247
    // Vanilla interpolation of __BASE__##__LINE__ would produce __BASE____LINE__
    // I still can't figure out why it works, but it has to do with macro resolution ordering
    #define PP_CAT(a, b) PP_CAT_I(a, b)
    #define PP_CAT_I(a, b) PP_CAT_II(~, a ## b)
    #define PP_CAT_II(p, res) res
    
    #define UNIQUE_NAME(base) PP_CAT(base, __COUNTER__)
    

    __COUNTER__ is rumored to have portability issues. If so, you can use __LINE__ instead and as long as you aren't calling the macro more than once per line or sharing the names across compilation units, you will be just fine.

    0 讨论(0)
  • 2020-12-01 08:57

    Instead of having the preprocesser create a name, you could possibly let the macro user give you a name.

    #define MY_MACRO(varname) int varname = getCurrentTime();
    
    0 讨论(0)
提交回复
热议问题