Determine if a (c++) iterator is reverse

后端 未结 2 1063
感情败类
感情败类 2020-12-20 10:09

I want a mechanism to determine in compile time whether an iterator is reverse or not.

Iterator traits can only help with the category of an iterat

相关标签:
2条回答
  • 2020-12-20 10:42
    #include <iterator>
    #include <type_traits>
    
    template<typename Iter>
    struct is_reverse_iterator : std::false_type { };
    
    template<typename Iter>
    struct is_reverse_iterator<std::reverse_iterator<Iter>>
    : std::integral_constant<bool, !is_reverse_iterator<Iter>::value>
    { };
    

    You could also specialize the trait for any user-defined iterators that are reverse iterators.

    0 讨论(0)
  • 2020-12-20 10:46

    A simple method. It is easy to use and can determine if something is a reverse iterator or not, and can differentiate between const reverse iterators if needed.

    #include <iostream>
    
    template<typename Container, typename T>
    using IsRegRevIter = std::is_same<T,typename Container::reverse_iterator>;
    
    template<typename Container, typename T>
    using IsConstRevIter = std::is_same<T,typename Container::const_reverse_iterator>;
    
    template<typename Container, typename T>
    struct IsRevIter
    {
         const static bool value = IsRegRevIter<Container,T>::value
              || IsConstRevIter<Container,T>::value;
    };
    
    int main()
    {
         using Container = std::list<int>;
         Container myList = {1,2,3,4,5,6};
    
         auto RI = myList.rbegin();
         auto I = myList.begin();
    
         std::cout << std::endl << std::boolalpha << IsRevIter<Container,decltype(RI)>::value; //true
         std::cout << std::endl << std::boolalpha << IsRegRevIter<Container,decltype(RI)>::value; //true
         std::cout << std::endl << std::boolalpha << IsConstRevIter<Container,decltype(RI)>::value; //false (it is not const).
         std::cout << std::endl << std::boolalpha << IsRevIter<Container,decltype(I)>::value; //false
    
    return 0;
    
    }
    

    output:
    false
    true
    false
    false

    0 讨论(0)
提交回复
热议问题