【问题标题】:Metaprogramming, wrong number of template arguments元编程,模板参数数量错误
【发布时间】:2017-07-21 03:23:22
【问题描述】:

我正在尝试 C++ 元编程。我有一个 TypeList 类,它包含一个头类型和一个尾类型,它是另一个 TypeList 或列表末尾的 NullType。

我还有一个 IntegerList 类,它是 Integers 上的指针列表(嗯,它是一个日志记录系统,但我尽可能多地删除了代码,并且 Integer* 元素替换了 Logger* 元素)

我的文件无法编译,因为 g++ 抱怨我使用了“错误数量的模板参数(1,应该是 2)”,我不明白为什么。

我哪里做错了?我刚刚从我信任的网站上复制了一些代码,它应该可以工作......我主要决定使用元编程,因为它似乎是一件非常有趣的事情,但我已经开始失去理智了^^。

提前谢谢你。

PS。我有一个非常旧的 g++ 编译器,我无法更改(2006 年),但是 2013 年的另一个 g++ 给了我同样的错误。

PS2。我认为这种寒冷不会编译,因为 Integer 不是一个类,但是我在一个真正的类中得到了同样的错误,所以我相信我的错误发生在这个被检查之前。

整数列表.hpp:

#include <list>

typedef int Integer;

class NullType
{
};

template<class H, class T>
class TypeList
{
    typedef H Head;
    typedef T Tail;
};

template<class T>
struct IntegerList : public std::list<Integer*>
{
};

template<>
struct IntegerList<NullType> : public std::list<Integer*>
{
};

template <class H, class T>
struct IntegerList<TypeList<typename H, typename T> > :  public std::list<Integer*>
{ //                                              ^ error right there
  typedef TypeList<typename H, typename T> List_t;
  typedef typename H Head_t;
  typedef typename T Tail_t;

  IntegerList()
  {
    push_back( new Head_t );
    IntegerList<Tail_t> tmp;
    merge( tmp );
  }

  ~IntegerList()
  {
    IntegerList<List_t>::iterator it;
    for ( it=begin(); it!=end(); ++it )
      delete *it;
  }
};

main.cpp:

#include "IntegerList.hpp"

int main(int argc, char **argv)
{  
   // wrong number of template arguments (1, should be 2)
  IntegerList<TypeList<Integer, NullType> > mylist;
}

【问题讨论】:

  • 你的错误是什么,为什么 TypeList 只是一个类型的类? (另一个 Null 类)

标签: c++


【解决方案1】:

问题似乎是你在IntegerListTypeList的用法上洒了太多typenames。以下编译:

template <class H, class T>
struct IntegerList<TypeList< H,  T> > :  public std::list<Integer*>
{ 
  typedef TypeList< H,  T> List_t;
  typedef H Head_t;
  typedef T Tail_t;
  . . .
}

完整示例http://coliru.stacked-crooked.com/a/5086e3015dc12ea0

【讨论】:

  • 顺便说一句,无论您在哪里使用 11 年的编译器,您都应该考虑退出或要求升级。
  • 我有一个 2003 年的 :-(
猜你喜欢
  • 2019-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多