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

I have a function that expects a templated iterator type.

It currently dereferences the iterator to inspect the type being iterated.

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

  ...
}

I recently discovered that several of the standard iterator types, such as std::insert_iterator define *i as simply a reference to i.

That is, sizeof(*i) is the size of the iterator itself; the same as sizeof(i) or sizeof(***i)

Is there a universal way (supporting C++ 03) to determine the size or type of objects being iterated by any standard iterator?



Solution 1:[1]

This is what the iterator_traits are for.

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

Edit: This does not work for all Output Iterators.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Josie Thompson