0

因此,我试图围绕 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... 参数。

静态方法用于类似execDetours 的系统中,它替换 WINAPI 函数,然后将其代理给std::function委托。

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

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

4

1 回答 1

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

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

template<typename FinalPatch, typename Func>
class PatchN;

template<typename FinalPatch, typename ReturnType, typename... Ps>
class PatchN<FinalPatch, ReturnType(Ps...)>;
于 2013-09-29T23:22:03.657 回答