类定义中的可变参数模板

时间:2013-09-29 23:12:59

标签: c++ c++11 variadic-templates

所以我试图围绕C ++中新的可变参数模板,我想知道我是否可以用它来简化我的一些代码。我有这样的事情:

template<typename FinalPatch,typename ReturnType, typename P1>
class Patch1: public PatchBase
{
   public:
      typedef Patch1<FinalPatch,ReturnType,P1> patch_type;
      typedef ReturnType(WINAPI* FuncType)( P1 );
      typedef std::function<ReturnType(P1)> function_type;


      static ReturnType __stdcall exec( P1 p1 )
      {
         return _function(p1);
      }
};

template<typename FinalPatch,typename ReturnType, typename P1, typename P2>
class Patch2: public PatchBase
{
   public:
      typedef Patch2<FinalPatch,ReturnType,P1,P2> patch_type;
      typedef ReturnType(WINAPI* FuncType)( P1, P2 );
      typedef std::function<ReturnType(P1,P2)> function_type;

      static ReturnType __stdcall exec( P1 p1, P2 p2 )
      {
         return _function(p1, p2);
      }
};

直到大约10 P ......参数。

在类似Detours的系统中使用exec静态方法,它替换WINAPI函数,然后将其代理到std::function委托。

FuncType表示“正常”函数指针。

是否可以使用可变参数模板将其减少为单个类?如果是这样,怎么样?

1 个答案:

答案 0 :(得分:2)

有些事情:

template<typename FinalPatch,typename ReturnType, typename... Ps>
class PatchN: public PatchBase
{
   public:
      typedef PatchN patch_type;
      typedef ReturnType(WINAPI* FuncType)( Ps... );
      typedef std::function<ReturnType(Ps...)> function_type;
      // more "modern" C++11 notation
      //using patch_type = PatchN;
      //using FuncType = ReturnType(WINAPI*)(Ps...);
      //using function_type = std::function<ReturnType(Ps...)>;

      static ReturnType __stdcall exec( Ps... ps )
      {
         return _function(ps...);
      }
      // or, using perfect forwarding:
      //static ReturnType __stdcall exec( Ps&&... ps )
      //{
      //   return _function(std::forward<Ps>(ps)...);
      //}
};

通常,函数类型是从单个模板参数中提取的(例如在std::function中),例如

template<typename FinalPatch, typename Func>
class PatchN;

template<typename FinalPatch, typename ReturnType, typename... Ps>
class PatchN<FinalPatch, ReturnType(Ps...)>;