编辑:我已经编辑了示例以更好地类似于我遇到的问题,现在该函数取决于常规参数(而不仅仅是模板参数),这意味着无法在编译时进行计算。
我用手写类型列表写了一些代码,现在我们已经开始使用boost,我正试图将它移到mpl
库中。
我似乎找不到任何像样的文档,mpl::list
甚至无法将代码移植到boost::mpl
. 我有一种感觉,即使(如果?)我确实成功地移植了代码,它仍然不会是惯用的。能否请您告诉我应该如何编写以下boost
代码(请注意,这不是实际代码,这是人为的简化)。
原始代码 (codepad.org 粘贴)
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;
}
尝试使用 Boost 失败 (codepad.org 粘贴)
#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;
}