Edit: I've edited the sample to better resemble the problem I have, now the function depends on a regular parameter (and not only on template parameters) which means that the computations can't be made at compile time.
I wrote some code with a hand written typelist and now we've started using boost and I'm trying to move it to the mpl
library.
I can't seem to find any decent documentation for mpl::list
and I'm even failing to port the code to boost::mpl
. I've got the feeling that even when (if?) I do succeed in porting the code it will still not be idiomatic. Can' you please let me know how the following should be written with boost
(note that this is not the actual code, it's a contrived simplification).
Original code (codepad.org paste)
class nil {};
template <class Head, class Tail = nil>
struct type_list {
typedef Head head;
typedef Tail tail;
};
template <class List>
struct foo;
template <class Head, class Tail>
struct foo<type_list<Head, Tail> >{
template <class T>
static void* bar(T* obj, size_t size)
{
if (sizeof(Head) == size)
return reinterpret_cast<Head*>(obj);
// Otherwise check the rest of the list
return foo<Tail>::bar(obj, size);
}
};
template <>
struct foo<nil>
{
template <class T>
static void* bar(T*, size_t) { return NULL; }
};
#include <iostream>
int main()
{
int n = 3;
void *p = foo<type_list<char, type_list<bool,
type_list<double, type_list<long> > > >
>::bar(&n, 4);
std::cout<< p << std::endl;
}
Failed Attempt to use Boost (codepad.org paste)
#include <boost/mpl/list.hpp>
template <class List>
struct foo{
template <class T>
static void* bar(T* obj, size_t size)
{
typedef typename boost::mpl::front<List>::type type;
if (sizeof(type) == size)
return reinterpret_cast<type*>(obj);
// Otherwise check the rest of the list
return foo<typename List::next>::bar(obj, size);
}
};
template <>
struct foo<boost::mpl::list0<boost::mpl::na> >
{
template <class T>
static void* bar(T*)
{
return NULL;
}
};
#include <iostream>
int main()
{
int n = 3;
void *p = foo<boost::mpl::list<char, bool, double, long> >::bar(&n, 4);
std::cout << p << std::endl;
}