如何检测类型是迭代器还是const_iterator [英] how to detect if a type is an iterator or const_iterator

查看:162
本文介绍了如何检测类型是迭代器还是const_iterator的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道,如果有一种方法来检查在编译时是否一个类型T的一些迭代器类型是一个const_iterator,或不。迭代器在迭代器和const迭代器之间定义的类型(value_type,pointer,...)有什么区别吗?



我想实现这样: / p>

  typedef std :: vector< int> T; 

is_const_iterator< T :: iterator> :: value // is false
is_const_iterator< T :: const_iterator> :: value // is true


解决方案

C ++ 03解决方案:



因为没有答案似乎是正确的,这里是我尝试使用GCC:

  template< typename T& 
struct is_const_pointer {static const bool value = false; };

template< typename T>
struct is_const_pointer< const T *> {static const bool value = true; };

template< typenameTimer>
struct is_const_iterator
{
typedef typename std :: iterator_traits< TIterator> ::指针指针;
static const bool value = is_const_pointer< pointer> :: value;
};

示例:

 code> int main()
{
typedef std :: vector< int> :: iterator it_type;
typedef std :: vector< int> :: const_iterator const_it_type;

std :: cout<< (is_const_iterator< it_type> :: value)<< std :: endl;
std :: cout<< (is_const_iterator< const_it_type> :: value)<< std :: endl;
}

输出:

  0 
1

在线演示: http://ideone.com/TFYcW


I'm wondering, if there is a way to check at compile time whether a type T of some iterator type is a const_iterator, or not. Is there some difference in the types that iterators define (value_type, pointer, ...) between iterators and const iterators?

I would like to achieve something like this:

typedef std::vector<int> T;

is_const_iterator<T::iterator>::value       // is false
is_const_iterator<T::const_iterator>::value // is true

解决方案

C++03 Solution:

As none of the answer seems correct, here is my attempt which is working with GCC:

template<typename T>
struct is_const_pointer { static const bool value = false; };

template<typename T>
struct is_const_pointer<const T*> { static const bool value = true; };

template <typename TIterator>
struct is_const_iterator
{
    typedef typename std::iterator_traits<TIterator>::pointer pointer;
    static const bool value = is_const_pointer<pointer>::value;
};

Example:

int main()
{
    typedef std::vector<int>::iterator it_type;
    typedef std::vector<int>::const_iterator const_it_type;

    std::cout << (is_const_iterator<it_type>::value) << std::endl;
    std::cout << (is_const_iterator<const_it_type>::value) << std::endl;
}

Output:

0
1

Online Demo : http://ideone.com/TFYcW

这篇关于如何检测类型是迭代器还是const_iterator的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆