如果您愿意部分专门针对容器,您可以在当前标准中执行此操作,例如...
#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
您的迭代器存在。