小编mad*_*ina的帖子

如何打印通用 std::list 迭代器?

我希望能够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迭代器,以免发生冲突?

c++ templates iterator c++-standard-library c++17

6
推荐指数
2
解决办法
243
查看次数

标签 统计

c++ ×1

c++-standard-library ×1

c++17 ×1

iterator ×1

templates ×1