首页 > 解决方案 > 错误:参数打包类模板中类模板的参数过多

问题描述

我创建了一个主模板和两个特化:一个用于 void 类型,另一个是用于不同参数类型的参数包。

后台是一个“连接”引擎,用来连接返回void的成员函数,所以我不需要返回类型,只需要参数类型。这些类就像包装器一样,提供了一个语法友好的静态函数来创建具体的链接。

所以我的代码如下所示:


  /**
   * CalleeCreator class, primary template
   */
  template <typename T> class CalleeCreator;

  template <typename... TParams>
  class CalleeCreator<TParams...> final
  {
    public:
      template <typename TObject, void(TObject::*Function)(TParams...)>
      constexpr static void create(const char*name, TObject& instance)
      {
        new Callee< void (TObject::*)(TParams...), Function>( name, instance);
      }
  };

  template <>
  class CalleeCreator<void> final
  {
      template <typename TObject, void(TObject::*Function)(void)>
      constexpr static void create(const char* name, TObject& instance)
      {
        new Callee< void (TObject::*)(void), Function>( name, instance);
      }
  }; 

一旦我打电话给这样的事情:

CalleeCreator<uint8_t, uint16_t>::create<Object,
    &Object::method> ("test", *this);

我得到那个编译错误:错误:类模板的参数太多

打电话时

CalleeCreator<void>::create<Object,
    &Object::method> ("test", *this);

按预期工作

我不明白的是,我创建了另一个具有返回类型和相同主模板的版本:

  template <typename TReturn, typename... TParams>
  class CalleeCreator<TReturn(TParams...)> final
  {
    public:
      template <typename TObject, TReturn(TObject::*Function)(TParams...)>
      constexpr static void create(ConstCharPtr name, TObject& instance)
      {
          new Callee< TReturn (TObject::*)(TParams...), Function>( name, instance);
      }
  };

  template <typename TReturn>
  class CalleeCreator<TReturn(void)> final
  {
    public:
      template <typename TObject, TReturn(TObject::*Function)(void)>
      constexpr static void create(ConstCharPtr name, TObject& instance)
      {
          new Callee< TReturn (TObject::*)(void), Function>( name, instance);
      }
  };

如果我打电话给他们,一切都很好并且工作:

CalleeCreator<void(uint8_t, uint16_t)>::create<Object,
        &Object::method> ("test", *this);

我不明白我在这里做错了什么。

此外,Callee 类可以查看模板和构造函数。


/** Class Callee, primary
 */
template <typename T, T> class Callee;


template <typename TObject, typename... TParams,
          void (TObject::*Function)(TParams...)>
class Callee<void (TObject::*)(TParams...), Function> final
{
  public:
    Callee(const char* name, TObject& instance){}
};

当然,还有一个 Callee 类,其返回类型也适用于其他解决方案。

标签: c++templatesparameter-pack

解决方案


您只需要一个主要的可变参数类模板:

template <typename... TParams>
class CalleeCreator final
{
    // ...
};

您不需要部分专业化,也不需要专门R(void)化 - 这是一个古老的(来自 C),在 C++ 中编写一个采用 0 参数的函数类型的方法是使用空括号。


推荐阅读