How to use variadic templates to make a generic Lua function wrapper?

Viewed 1886

For my current project, I've been writing a lot of C/C++ to Lua wrappers. A large number of these are simple setters and getters, so I managed to write some templates that make it easy to generate these, like so:

//        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> }, 
    ...
};

I would like to do something similar for simple function wrappers for arbitrary functions too. For example, it would be nice to be able to do this:

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> }, 
    ...
};

The idea is that the template effectively turn out to be this when compiled:

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;
}

I've tried just using the ... expander, the problem for me is the integer index values to map to the proper arguments. I can't think of a way to get them working right. Is such a thing even possible?

(there is a little bit of magic going on here already; I wrote some templated wrappers for things like lua_push and lua_check. All of those existing wrappers can be found here)

2 Answers
Related