C++ 函数作为模板参数,加上可变模板参数

C++ 函数作为模板参数,加上可变模板参数,c++,c++11,C++,C++11,我正在编写一个通用函数包装器,它可以将任何函数包装成lua风格的调用,其形式如下 int lua_函数(lua_状态*L) 我希望包装器函数是动态生成的,所以我考虑将函数作为模板参数传递。如果您知道参数的数量(例如,2),则这是微不足道的: template <typename R, typename Arg1, typename Arg2, R F(Arg1, Args)> struct wrapper 用户必须写入 func_type<decltype(sin)>:

我正在编写一个通用函数包装器,它可以将任何函数包装成lua风格的调用,其形式如下

int lua_函数(lua_状态*L)

我希望包装器函数是动态生成的,所以我考虑将函数作为模板参数传递。如果您知道参数的数量(例如,2),则这是微不足道的:

template <typename R, typename Arg1, typename Arg2, R F(Arg1, Args)>
struct wrapper
用户必须写入

func_type<decltype(sin)>::func<sin>::apply
func\u类型::func::应用
这很乏味。
问题是:有没有更好、更方便用户的方法?(我不能使用函数模板来包装整个内容,因为函数参数不能用作模板参数。)

正如@Juraj在他的评论中所说,函数指针可以是模板参数,请参见以下简单示例:

#include <iostream>
#include <boost/typeof/typeof.hpp>

void f(int b, double c, std::string const& g)
{
  std::cout << "f(): " << g << std::endl;
}

template <typename F, F* addr>
struct wrapper
{
  void operator()()
  {
    std::string bar("bar");
    (*addr)(1, 10., bar);
  }  
};

int main(void)
{
  wrapper<BOOST_TYPEOF(f), &f> w;
  w();
  return 0;
}
#包括
#包括
空f(整数b,双c,标准::字符串常量和g)
{

std::cout类似于
std::function
std::result\u的

template<typename Signature>
struct wrapper; // no base template

template<typename Ret, typename... Args>
struct wrapper<Ret(Args...)> {
    // instantiated for any function type
};
以上使用gcc-4.5进行编译。
实现apply(可变地)弹出参数祝您好运(如果您对此有疑问,请给我留言)你认为使用LuabDink?< /P>我认为函数指针可以是模板参数。它至少对MSVC起作用。这里类似的问题正在这里得到解决:谢谢卢克,我认为这是我们可以不用宏的。BTW,为了我的目的(简单的C++函数包),写一个“应用”。很简单,我只需编写一组名为extract_arg的模板专门化,然后执行statci apply(lua_State*L){P(extract_arg(L)…;}
func_type<decltype(sin)>::func<sin>::apply
#include <iostream>
#include <boost/typeof/typeof.hpp>

void f(int b, double c, std::string const& g)
{
  std::cout << "f(): " << g << std::endl;
}

template <typename F, F* addr>
struct wrapper
{
  void operator()()
  {
    std::string bar("bar");
    (*addr)(1, 10., bar);
  }  
};

int main(void)
{
  wrapper<BOOST_TYPEOF(f), &f> w;
  w();
  return 0;
}
template<typename Signature>
struct wrapper; // no base template

template<typename Ret, typename... Args>
struct wrapper<Ret(Args...)> {
    // instantiated for any function type
};
template<typename Sig, Sig& S>
struct wrapper;

template<typename Ret, typename... Args, Ret(&P)(Args...)>
struct wrapper<Ret(Args...), P> {
    int
    static apply(lua_State*)
    {
        // pop arguments
        // Ret result = P(args...);
        // push result & return
        return 1;
    }
};

// &wrapper<decltype(sin), sin>::apply is your Lua-style wrapper function.