13

重複の可能性:
iterator から const_iterator を取得する

const_iteratorから対応するものを返すメタ関数を書きたいiterator

template <class Iterator>
struct get_const_iterator
{
    typedef ??? type;
};
  • get_const_iterator<int*>::typeでなければなりませんconst int*
  • get_const_iterator<const int*>::typeでなければなりませんconst int*
  • get_const_iterator<int* const>::typeconst int*またはである必要がありますconst int* const。気にしません
  • get_const_iterator<std::list<char>::iterator>::typeでなければなりませんstd::list<char>::const_iterator

これは、iterator_traitsそれらの有無にかかわらず行うことができますか?

編集:iterator 2つのコンテナが同じタイプである場合、それらもであると仮定しましょうconst_iterator。理論的には完全に正しいとは言えませんが、これは合理的な仮定だと思います。

4

2 に答える 2

1

次のように、コンテナに部分的に特化したい場合は、現在の標準でそれを行うことができます...

#include <vector>
#include <list>
#include <iterator>

// default case
template <typename Iterator, typename value_type, typename container_test = Iterator>
struct container
{
  typedef Iterator result;
};

// partial specialization for vector
template <typename Iterator, typename value_type>
struct container<Iterator, value_type, typename std::vector<value_type>::iterator>
{
  typedef typename std::vector<value_type>::const_iterator result;
};

// partial specialization for list, uncomment to see the code below generate a compile error
/* template <typename Iterator, typename value_type>
struct container<Iterator, value_type, typename std::list<value_type>::iterator>
{
  typedef typename std::list<value_type>::const_iterator result;
}; */

// etc.

template <typename Iterator>
struct get_const
{
  typedef typename container<Iterator, typename std::iterator_traits<Iterator>::value_type>::result type;
};

int main(void)
{
  std::list<int> b;
  b.push_back(1);
  b.push_back(2);
  b.push_back(3);
  get_const<std::list<int>::iterator>::type it1 = b.begin(), end1 = b.end();
  for(; it1 != end1; ++it1)
    ++*it1; // this will be okay

  std::vector<int> f;
  f.push_back(1);
  f.push_back(2);
  f.push_back(3);

  get_const<std::vector<int>::iterator>::type it = f.begin(), end = f.end();
  for(; it != end; ++it)
    ++*it; // this will cause compile error

}

もちろん、上記のスティーブのポイントを繰り返します。また、要件はiterator_traitsイテレータが存在することです。

于 2011-07-05T17:59:50.373 に答える
1

C ++ 0xでそれを行うことができます

template <typename Container>
Container container (typename Container :: iterator);

template <typemame Iterator>
struct get_const_iterator
{
    typedef decltype (container (Iterator())) :: const_iterator type;
};

私はスティーブに同意し始めていますが、異なるコンテナが同じ反復子タイプを持つ可能性があるため、これは一般的な解決策ではありません。

于 2011-07-05T16:32:10.223 に答える