c++ stl traits const T*偏特化。
本文介绍了c++ stl traits const T*偏特化。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
如下:
template <class I>
struct iterator_traits
{
typedef typename I::value_type value_type;
}
//针对指向常数对象的指针的特例化
template <class T>
struct iterator_traits<const T*>
{
typedef T value_type;
}
这里想到得到迭代器相关的value_type,为什么把const int转换成int呢?我们想得到是类型信息,虽然得到的(这个类型的变量)无法修改,为什么说他没有用(stl源码剖析书上说的)
以上,希望大家帮忙讲一下。谢谢了。?
这个是源码:
template <class _Tp>
struct iterator_traits<const _Tp*> {
typedef random_access_iterator_tag iterator_category;
//这里:
typedef _Tp value_type;
typedef ptrdiff_t difference_type;
typedef const _Tp* pointer;
typedef const _Tp& reference;
};
就是上面value_type处,为什么把const Tp* 的const属性去掉。
解决方案
是这样的, traits(萃取)的目的是用来在编译期能静态的取得对象的一些固有特性
没太明白你想表达什么,你说为什么把const int转换成int,实际上const是由下面的来定义的
template <class T>
struct iterator_traits<const T*>
{
typedef const T const_value_type;
//你可以定义更多的,traits出更多的类型
}
这篇关于c++ stl traits const T*偏特化。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文