4

テンプレート化されたイテレータ型を期待する関数があります。

現在、反復子を逆参照して、反復される型を調べています。

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私は最近、 defineなどの標準イテレータ型のいくつかが*i単に への参照であることを発見しましたi

つまりsizeof(*i)、イテレータ自体のサイズです。sizeof(i)またはと同じsizeof(***i)

標準イテレータによって反復されるオブジェクトのサイズまたはタイプを決定する普遍的な方法 (C++ 03 をサポートする) はありますか?

4

2 に答える 2

4

これiterator_traitsが目的です。

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

編集:これはすべての出力イテレータで機能するわけではありません。

于 2012-11-28T18:28:48.913 に答える
2

value_typeOutputIterator から値を抽出する方法がないため、なぜ OutputIteratorが必要なのかわかりません。ただし、3 つの挿入イテレータ アダプタはすべてvalue_typeであると定義し、型メンバーvoidを提供するため、 ofが であることが判明した場合、of にcontainer_typeフォールバックできます。value_typeT::container_typevalue_typeTvoid

(「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> {}; 
于 2012-11-28T19:28:07.363 に答える