2011-08-02 65 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