您的位置:首页 > 理论基础 > 计算机网络

网络游戏服务器开发::用模板偏特化封装C++调用lua的代码

2010-06-08 10:15 736 查看
主要用到了模板偏特化,下面放出代码。

/*
* =====================================================================================
*
*       Filename:  LuaCall.h
*
*    Description:  luaCall
*
*        Version:  1.0
*        Created:  2010年06月03日 09时27分55秒
*       Revision:  none
*       Compiler:  gcc
*
*         Author:  wangfan (), wangfan1985@gmail.com
*        Company:
*
* =====================================================================================
*/
#include "lua.hpp"
#include "tolua++.h"
template<typename T>
struct PushValue
{
static inline void push(lua_State* L,T t);
};
template<>
inline void PushValue<uint32_t>::push(lua_State* L,uint32_t t)
{
tolua_pushnumber(L, t);
}
template<>
inline void PushValue<char*>::push(lua_State* L,char* t)
{
tolua_pushstring(L, t);
}
template<typename T>
struct PushValue<T*>
{
static inline void push(lua_State* L,T* t)
{
const char* temp = typeid(t).name();
++temp;
if(*temp >= '0' && *temp <= '9')
{
++temp;
if(*temp >= '0' && *temp <= '9')
++temp;
}
tolua_pushusertype(L, t, temp);
}
};
static inline void luaCall(lua_State* L,const char *name)
{
lua_getglobal(L, name);
int ret = lua_pcall(L, 1, 0, 0);
if(ret != 0)
{
const char* error = lua_tostring(L, -1);//打印错误结果
printf("[%u]%s",ret,error);
lua_pop(L, 1);
}
}
template<typename T1>
static inline void luaCall(lua_State* L,const char *name,T1 t1)
{
lua_getglobal(L, name);
PushValue<T1>::push(L,t1);
int ret = lua_pcall(L, 1, 0, 0);
if(ret != 0)
{
const char* error = lua_tostring(L, -1);//打印错误结果
printf("[%u]%s",ret,error);
lua_pop(L, 1);
}
}
template<typename T1,typename T2>
static inline void luaCall(lua_State* L,const char *name,T1 t1,T2 t2)
{
lua_getglobal(L, name);
PushValue<T1>::push(L,t1);
PushValue<T2>::push(L,t2);
int ret = lua_pcall(L, 2, 0, 0);
if(ret != 0)
{
const char* error = lua_tostring(L, -1);//打印错误结果
printf("[%u]%s",ret,error);
lua_pop(L, 1);
}
}


PushValue是用来选择参数的模板,用模板偏特化来决定调用tolua_pushnumber还是tolua_pushusertype

typeid可以得到类名字,都是在编译期决定的。

luaCall就是要用的函数啦。返回值是void,也可以对有其他返回值的需求进行封装。

如果以后还需要使用其它类型,只需要实现一个特化的PushValue就行了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐