我希望能够std::list通过打印其值来打印任何迭代器。我的初始代码如下所示:
template<typename T>
std::ostream& operator<<(std::ostream& os, const typename std::list<T>::const_iterator& x)
{
return os << "&" << *x;
}
Run Code Online (Sandbox Code Playgroud)
哪个不起作用,因为编译器无法确定参数T。然后我尝试使它在迭代器类型本身上通用,并iterator_traits用于将其限制为迭代器。
template<
typename It,
typename = typename std::iterator_traits<It>::value_type
>
std::ostream &operator<<(std::ostream &os, const It &x)
{
return os << "&" << *x;
}
Run Code Online (Sandbox Code Playgroud)
但是,当然,我得到了两个相互冲突的实现std::ostream << *const char,因为指针也是迭代器。如何将实现限制为std::list迭代器,以免发生冲突?