【发布时间】:2012-07-21 07:53:08
【问题描述】:
对于我当前的项目,我一直在为 Lua 包装器编写大量 C/C++。其中很多都是简单的 setter 和 getter,所以我设法编写了一些模板来轻松生成它们,如下所示:
// Class Return Field
template <typename T, typename U, U T::*Member>
int luaU_get(lua_State* L)
{
T* obj = luaW_check<T>(L, 1);
luaU_push<U>(L, obj->*Member);
return 1;
}
static luaL_reg Foo_Table[] =
{
...
// Now I can just use this generic template to avoid
// writing simple getter functions
{ "getbar", luaU_get<Foo, Bar, &Foo::bar> },
...
};
我也想为任意函数的简单函数包装器做类似的事情。例如,如果能够做到这一点,那就太好了:
template <typename T, typename U, U (T::*Func)(), typename... Args>
int luaU_func(lua_State* L)
{
// ...?
}
static luaL_reg Foo_Table[] =
{
...
{ "baz", luaU_func<Foo, int, &Foo::baz, int, float> },
...
};
这个想法是模板在编译时实际上变成了这样:
int luaU_func(lua_State* L)
{
luaU_push<int>(L, luaW_check<Foo>(L, 1)->baz(luaU_check<int>(L, 2), luaU_check<float>(L, 3)));
return 1;
}
我试过只使用... 扩展器,对我来说问题是整数索引值映射到正确的参数。我想不出让他们正常工作的方法。这样的事情有可能吗?
(这里已经有一点点神奇了;我为 lua_push 和 lua_check 编写了一些模板化的包装器。所有这些现有的包装器都可以在 here 找到)
【问题讨论】:
-
你看过luabind吗?
-
你是在建议我使用 luabind 吗?或者他们是否解决了我可以参考的类似问题? (出于多种原因,我对在我的项目中使用 luabind 不感兴趣。)
-
我只是不确定你是否知道。无论如何,对于参数和索引问题,here is the basic idea.
标签: c++ c++11 lua variadic-templates member-functions