声明一个C++的模板语法是,template 〈class c…〉 …
如果要向模板传递的参数类型比较多,这个template表就会很长,用起来很不方便。这时候可以用上template参数的压缩格式。
压缩格式的用法很简单。就是在外部定义一个struct, 把传给模板的参数,定义到struct 里面,这样就只要传一个struct 好了。
比如原来的template是这样的:
template<class Node_type, class Value_type> …
可以把传给template两个参数类型收集到一个struct里面去。然后再把这个struct传给template:
struct my_value {…};
struct my_node {…};
struct my_schema {
typedef my_node Node_type;
typedef my_value Value_type;
};
template 〈class Schema〉 class X
{
typedef Schema::Node_type Node_type;
typedef Schema::Value_type Value_type;
…
};
使用的时候,用template <my_schema>…,这个用template <my_node, my_value>…有相同的效果。
作为例子,下面抄录了一段STL中的代码:
template<typename _Iterator, typename _Sequence>
class _Safe_iterator : public _Safe_iterator_base
{
typedef _Safe_iterator _Self;
/*. ... ......... .. ..... .. ... ......... ... ........ .......
. ... ..........
*/
enum _Distance_precision
{
__dp_equality, //. ... ....... ........ ......... ....
__dp_sign, //. ... ......... ........ ... ........
__dp_exact //. ... ......... ........ .........
};
//. ... .......... ........
_Iterator _M_current;
//. ......... .. .... .. . ........ .........
bool
_M_constant() const
{
typedef typename _Sequence::const_iterator const_iterator;
return __is_same<const_iterator, _Safe_iterator>::value;
}
typedef std::iterator_traits<_Iterator> _Traits;
public:
typedef _Iterator _Base_iterator;
typedef typename _Traits::iterator_category iterator_category;
typedef typename _Traits::value_type value_type;
typedef typename _Traits::difference_type difference_type;
typedef typename _Traits::reference reference;
typedef typename _Traits::pointer pointer;
//. ..... ... ........ .. ........ ... ..........
_Safe_iterator() : _M_current() { }
...
};
里面一上来用了很多typedef。相当于把很多本来要通过template 参数表传递的参数先收集到_Traits,然后再传入一个_Traits。这样就简化了template参数传递。