//源码剖析的写法
template<typename Iterator>
struct iterator_traits
{
typedef typename Iterator::iterator_category iterator_category;
typedef typename Iterator::value_type value_type;
typedef typename Iterator::difference_type difference_type; //表示容器的最大容量
typedef typename Iterator::pointer pointer;
typedef typename Iterator::reference reference;
};
//找的项目的写法
template <class T>
struct has_iterator_cat
{
private:
struct two { char a; char b; };
template <class U> static two test(...); //...省略参数
template <class U> static char test(typename U::iterator_category* = 0);
public:
static const bool value = sizeof(test(0)) == sizeof(char);
};
template <class Iterator, bool>
struct iterator_traits_impl {};
template <class Iterator>
struct iterator_traits_impltrue> //偏特化版本
{
typedef typename Iterator::iterator_category iterator_category;
typedef typename Iterator::value_type value_type;
typedef typename Iterator::pointer pointer;
typedef typename Iterator::reference reference;
typedef typename Iterator::difference_type difference_type;
};
template <class Iterator, bool>
struct iterator_traits_helper {};
template <class Iterator>
struct iterator_traits_helpertrue>
: public iterator_traits_impltypename Iterator::iterator_category, input_iterator_tag>::value ||
std::is_convertible<typename Iterator::iterator_category, output_iterator_tag>::value>
{
};
//出错的函数
template<typename T>
template<typename Iter>
inline void List::copy_init(Iter first, Iter last)
{
node_ = base_allocator::allocate(1);
node_->unlink();
size_type n=mystl::distance(first, last); //只要有这个距离函数就会报错
size_ = n;
try
{
for (; n > 0; --n, ++first)
{
auto node = create_node(1);
link_nodes_at_back(node->as_base(), node->as_base());
}
}
catch (...)
{
clear();
base_allocator::deallocate(node_);
node_ = nullptr;
throw;
}
}
我按照源码剖析的写法,size_type n=mystl::distance(first, last); 使用这个函数时就会报错如下
错误全部指向我按照源码剖析写的iterator_traits。
想不明白这是为什么?我在vector容器中也是用了这个计算迭代器距离的函数,就没有问题