I was implenting a TypeList based on Loki, based on reading from:
http://aszt.inf.elte.hu/~gsd/halado_cpp/ch06s09.html
and saw this code from the site for IndexOf (to find the index of a type in the typelist):
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 };
};
It doesn't seem like that would work because nowhere do I see something comparing T as the list is recursively traversed. In my implementation it looks like this:
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;
};
and, in fact, always returns -1. If I think of it, imagine one has TypeList; then Tail will be NullType, so temp will be -1 by the specialization and then value will be -1..even if Head was char and I would have expected zero. What am I missing here?
Thanks
My implementation of Typelist is merely:
template<typename H, typename T>
struct Typelist
{
typedef H Head;
typedef T Tail;
};
I'm guessing this isn't Lokis, but With Joel's answer I got this working for me:
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;
};
Should be :
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 };
};
You try to find T at some Head in the recursive encoding of the list.