【发布时间】:2011-08-26 09:15:44
【问题描述】:
我正在编写一个通用函数包装器,它可以将任何函数包装成一个 lua 风格的调用,其形式为
int lua_function(lua_State *L)
我希望包装函数是即时生成的,所以我正在考虑将该函数作为模板参数传递。如果您知道参数的数量(例如 2),这很简单:
template <typename R, typename Arg1, typename Arg2, R F(Arg1, Args)>
struct wrapper
但是,我不知道数字,所以我请求可变参数模板参数的帮助
// This won't work
template <typename R, typename... Args, R F(Args...)>
struct wrapper
上面不会编译,因为可变参数必须是最后一个。所以我使用了两级模板,外层模板捕获类型,内层模板捕获函数:
template <typename R, typename... Args>
struct func_type<R(Args...)>
{
// Inner function wrapper take the function pointer as a template argument
template <R F(Args...)>
struct func
{
static int call( lua_State *L )
{
// extract arguments from L
F(/*arguments*/);
return 1;
}
};
};
这行得通,除了要包装一个类似的函数
double sin(double d) {}
用户必须写
func_type<decltype(sin)>::func<sin>::apply
这很乏味。 问题是:有没有更好、对用户更友好的方法呢? (我不能使用函数模板来包装整个东西,因为函数参数不能用作模板参数。)
【问题讨论】:
-
我认为函数指针可以是模板参数。它至少适用于 MSVC。与您类似的问题正在这里解决:stackoverflow.com/questions/4387971/….