发信人: huxw (米老鸭和唐老鼠), 信区: Programming
标 题: boost::iterator_adaptor (I)
发信站: BBS 水木清华站 (Sat May 18 23:27:33 2002)
内容很多, 一部分一部分来. 先说其中的typelist实现的原理。
I) Type-list, 类型列表. 很tricky的方法, 第一次看见是在loki库里
面. 有时候我们确实需要一个类型的列表, 可以简单的遍历访问. 而一般的
容器是不能储存类型的. 怎么办? 看下面.
首先, 这里的类型列表是怎么建立起来的? 很简单
template
struct cons_type {
typedef A first_type;
typedef B second_type;
};
这样的情况下, cons_type::first_type就是int, 而
second_type就是double. 而奇妙的作用在于cons_type的嵌套使用,
cons_type, long>::first_type 是
cons_type, 而first_type::first_type是int. 在这个
库中, 额外定义了一个end_of_list表示类表结束.明白了吗?明白了我
们就继续吧 ;)
然后介绍一个find_param模版, 可以从一个类型列表里面找出特定的类
型. 对于不支持偏特化的编译器, 方法如下:
template
struct find_param {
typedef typename find_param_helper1::type select1;
typedef typename select1::template select::type type;
};
其中
template struct find_param_helper1
{ typedef find_param_continue type; };
template <> struct find_param_helper1
{ typedef find_param_end type; };
而
struct find_param_continue {
template struct select {
typedef typename AssocList::first_type Head;
typedef typename Head::first_type Key1;
typedef typename Head::second_type Value;
typedef typename if_true::value)>::template
then typename find_param::type
然后介绍一个find_param模版, 可以从一个类型列表里面找出特定的类
型. 对于不支持偏特化的编译器, 方法如下:
template
struct find_param {
typedef typename find_param_helper1::type select1;
typedef typename select1::template select::type type;
};
其中
template struct find_param_helper1
{ typedef find_param_continue type; };
template <> struct find_param_helper1
{ typedef find_param_end type; };
而
struct find_param_continue {
template struct select {
typedef typename AssocList::first_type Head;
typedef typename Head::first_type Key1;
typedef typename Head::second_type Value;
typedef typename if_true::value)>::template
then typename find_param::type
>::type type;
};
};
struct find_param_end {
template
struct select { typedef detail::default_argument type; };
};
从以上代码综合看来, 当Key1和Key2是同一类型的时候, 就是模版嵌套
结束的时候, 否则, 模版不停嵌套展开, 知道找到合适的Key2(is_same)或者遇到
end_of_list(特化的模板)为止. if_true的模版在detail/select_type.hpp中,
很明了.
花开两朵, 如果是支持片特化的编译器, 那就简单的多了.
template struct find_param;
template
struct find_param { typedef default_argument type; };
template
struct find_param<:cons_type detail::cons_type value>, Rest>, Key> {
struct find_param { typedef default_argument type; };
template
struct find_param<:cons_type detail::cons_type value>, Rest>, Key> {
typedef Value type;
}; //偏特化, 表示Key和Key相同的情况
template
struct find_param<:cons_type detail::cons_type value>, Rest>, Key2> {
typedef typename find_param::type type;
}; //否则, 模版嵌套展开.
TypeList是现在也算是一种常见技巧了, 还是那本Modern C++ Design中提出来的,
建议有兴趣的去cuj上找来看更详细的说明, 主要是建立typelist的方法. ;)
--
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
※ 来源:·BBS 水木清华站 bbs.edu.cn·[FROM: 166.111.172.6]
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/10752043/viewspace-992189/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/10752043/viewspace-992189/