是否可以推断出 std::insert_iterator 的包含类型

Is it possible to deduce the contained type for std::insert_iterator?

本文关键字:iterator 包含 类型 insert 推断出 std 是否      更新时间:2023-10-16

我有一个函数,它需要一个模板化的迭代器类型。

它当前取消引用迭代器以检查正在迭代的类型。

template < typename Iterator >
void func( Iterator i )
{
  // Inspect the size of the objects being iterated
  const size_t type_size = sizeof( *i );
  ...
}

我最近发现几种标准迭代器类型,例如std::insert_iterator*i定义为对i的引用。

也就是说,迭代器本身的大小sizeof(*i);与sizeof(i)sizeof(***i)相同

是否有一种通用方法(支持C++ 03)来确定任何标准迭代器正在迭代的对象的大小或类型?

这就是

iterator_traits的用途。

typedef typename std::iterator_traits<Iterator>::value_type type;
const std::size_t type_size = sizeof(type);

编辑:这不适用于所有输出迭代器。

我不确定为什么你想要输出迭代器的value_type,因为无法从输出迭代器中提取值。但是,三个插入迭代器适配器都value_type定义为void并提供container_type类型成员,因此如果Tvalue_type结果是void,则可以回退到T::container_type value_type

(我所说的"value_type"是指std::iterator_traits<T::container_type>::value_typestd::iterator_traits<T>::value_type

或者,您可以不尝试使用输出迭代器,就好像它们具有值:)

编辑:SFINAE不是必需的:(即使没有C++11的美好)

template<typename U, typename T> struct helper {typedef U type;};
// ostream*_iterator handling courtesy Drew Dormann
template <typename T, typename charT, typename traits>
struct helper<void, std::ostream_iterator<T, charT, traits> > {typedef T type;};
template <typename charT, typename traits>
struct helper<void, std::ostreambuf_iterator<charT, traits> > {typedef charT type;};
// std::raw_storage_iterator still needs an override
// as well as any non-standard output iterators which don't define a container_type.
template<typename T> struct helper<void, T>
{typedef typename std::iterator_traits<typename T::container_type>::value_type type;};
typedef<typename It> struct my_value_type
  : public helper<typename std::iterator_traits<It>::value_type, It> {};