C ++ preprocessor metaprogramming: getting a unique value?

I use the behavior of C ++ global variable constructors to easily run code at startup. This is a very simple concept, but a little difficult to explain, so let me just insert the code:

struct _LuaVariableRegistration
{
    template<class T>
    _LuaVariableRegistration(const char* lua_name, const T& c_name) {
        /* ... This code will be ran at startup; it temporarily saves lua_name and c_name in a std::map and when Lua is loaded it will register all temporarily global variables in Lua. */
    }
};

However, manually creating an instance of this super ugly class every time you want to register a Lua global variable is cumbersome; so I created the following macro:

#define LUA_GLOBAL(lua_name, c_name) static Snow::_LuaVariableRegistration _____LuaGlobal ## c_name (lua_name, c_name);

So, all you have to do is put this in the global area of ​​the cpp file and everything works fine:

LUA_GLOBAL("LuaIsCool", true);

Come here! Now in Lua there LuaIsCoolwill be a variable initialized to true!

But here is the problem:

LUA_GLOBAL("ACCESS_NONE", Access::None);

What will happen:

static Snow::_LuaVariableRegistration _____LuaGlobalAccess::None ("ACCESS_NONE", &Access::None);

: (( c_name ; __LINE__, _____LuaGlobalAccess__LINE__ (.. ).

, - ?

PS: , , _, ; , , , - . , .

+3
1

, :

#define TOKENPASTE(x, y) x ## y
#define TOKENPASTE2(x, y) TOKENPASTE(x, y)

#define LUA_GLOBAL(lua_name, c_name) ... TOKENPASTE2(_luaGlobal, __LINE__) ...

__COUNTER__, , , , __LINE__ . , ISO C, gcc -ansi -pedantic.

+7

Source: https://habr.com/ru/post/1723635/


All Articles