根据以下内容,我鼓励基于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;
};
最佳答案
应该 :
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。
关于c++ - Loki IndexOf为TypeList的实现,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10625637/