从迭代器获取const_iterator

Arm*_*yan 13 c++ templates iterator stl template-meta-programming

可能重复:
从迭代器获取const_iterator

我想写一元函数返回相应的const_iteratoriterator

template <class Iterator>
struct get_const_iterator
{
    typedef ??? type;
};
Run Code Online (Sandbox Code Playgroud)
  • get_const_iterator<int*>::type 一定是 const int*
  • get_const_iterator<const int*>::type 一定是 const int*
  • get_const_iterator<int* const>::type必须是const int*const int* const,我不在乎
  • get_const_iterator<std::list<char>::iterator>::type 一定是 std::list<char>::const_iterator

等等

可以使用iterator_traits或不使用它们吗?

编辑:我们假设如果2个容器具有相同的iterator类型,那么它们也具有相同的const_iterator类型.我认为这是一个合理的假设,虽然理论上并不完全正确.

spr*_*aff 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;
};
Run Code Online (Sandbox Code Playgroud)

尽管我开始同意 Steve 的观点——这不是一个通用的解决方案,因为不同的容器可能具有相同的迭代器类型。

  • 另外,这仅满足@Armen 的最后一个要求。 (2认同)
  • @Martinho:公平地说,它尝试的部分是棘手的部分。从过去的问题来看,我认为 Armen 可能会部分专门化他的指针类型结构:-) (2认同)