2011-08-02 64 views
2

我有一个C++宏,看起来像这样函数名宏C++

#define lua_tpushstring(L,n,f) \ 
      (lua_pushstring(L, n), lua_pushstring(L, f)) 

我要那么它的工作原理是这样

#define lua_tpush(TYPE,L,n,f) \ 
      (lua_pushstring(L, n), lua_pushTYPE(L, f)) 

lua_tpush(boolean, L, "a", true); 
lua_tpush(string, L, "a", ""); 

什么是简单的变化进行修改?

+5

您是否考虑过使用模板? – sbi

+1

同意sbi。 DRY原则;如果我推“真”,我不需要重复自己,并告诉编译器我在推“bool”。但你甚至不需要模板;超载就足够了。你需要函数,虽然(宏的不要超载):'无效的LuaClass :: push(std :: string n,bool f){lua_pushstring(this-> L,n); lua_pushboolean(this-> L,f); }'等等 – MSalters

+0

@ MSalters:的确,由于功能如此微不足道,在这种情况下,重载可能同样好。但是,通常情况下,如果您需要许多类似的实现,模板会更好,因为您不必一遍又一遍地复制代码。 – sbi

回答

6

Token concatenation

#define lua_tpush(TYPE,L,n,f) (lua_pushstring(L, n), lua_push##TYPE(L, f)) 
3

TYPE之前把##

#define lua_tpush(TYPE,L,n,f) \ 
      (lua_pushstring(L, n), lua_push##TYPE(L, f)) 
        ^^^^^^ did you wanted ##TYPE here