为TypeList实现Loki IndexOf

时间:2012-05-16 19:47:27

标签: c++ templates metaprogramming loki

我正在基于Loki实现一个TypeList,基于以下内容:

http://aszt.inf.elte.hu/~gsd/halado_cpp/ch06s09.html

并从IndexOf网站上看到此代码(以查找类型列表中类型的索引):

template <class T>
struct IndexOf< NullType, T>
{
    enum { value = -1 };
};

template <class T, class Tail>
struct IndexOf< Typelist<Head, Tail>, T>
{
private:
    enum { temp = IndexOf<Tail, T>::value };
public:
    enum { value = (temp == -1) ? -1 : 1+temp };
};

看起来这似乎不起作用,因为我无处可见比较T的东西,因为列表是递归遍历的。在我的实现中它看起来像这样:

template<typename Tlist, typename T>
struct IndexOf
{
private:
  static const int temp = IndexOf<typename Tlist::Tail, T>::value;
public:
  static const int value = (temp == -1) ? -1 : 1 + temp;
};

template<typename T>
struct IndexOf<NullType, T>
{
  static const int value = -1;
};

并且实际上总是返回-1。如果我想到它,想象一个人有TypeList;然后Tail将是NullType,因此temp将通过专门化为-1,然后值将为-1 ..即使Head是char并且我预期为零。我在这里缺少什么?

由于


我的Typelist实现仅仅是:

template<typename H, typename T>
struct Typelist
{
  typedef H Head;
  typedef T Tail;
};

我猜这不是Lokis,但有了Joel的回答,我得到了这个让我感到满意:

template<typename Head, typename Tail, typename T>
struct IndexOfImpl
{
private:
  static const int temp = IndexOfImpl<typename Tail::Head, typename Tail::Tail, T>::value;
public:
  static const int value = (temp == -1) ? -1 : temp + 1;
};

template<typename T, typename Tail>
struct IndexOfImpl<T, Tail, T>
{
  static const int value = 0;
};

template<typename T>
struct IndexOfImpl<T, NullType, T>
{
  static const int value = 0;
};

template<typename Head, typename T>
struct IndexOfImpl<Head, NullType, T>
{
  static const int value = -1;
};

template<typename Tlist, typename T>
struct IndexOf
{
 public:
  static const int value = IndexOfImpl<typename Tlist::Head, typename Tlist::Tail, T>::value;
};

1 个答案:

答案 0 :(得分:1)

应该是:

template <class T>
struct IndexOf< NullType, T>
{
    enum { value = -1 };
};

template <class T, class Head, class Tail>
struct IndexOf< Typelist<Head, Tail>, T>
{
private:
    enum { temp = IndexOf<Tail, T>::value };
public:
    enum { value = (temp == -1) ? -1 : 1+temp };
};

template <class T, class Tail>
struct IndexOf< Typelist<T, Tail>, T>
{
public:
    enum { value = 0 };
};

您尝试在列表的递归编码中找到某个Head的T。