How to check if a template parameter is an iterator type or not?

后端 未结 5 1421
迷失自我
迷失自我 2020-12-17 19:21
template
struct is_iterator
{
    static const bool value = ??? // What to write ???
};

int main()
{
    assert(false == is_iterator::valu         


        
5条回答
  •  抹茶落季
    2020-12-17 19:54

    The original poster clarified that they are actually asking for a way to identify an InputIterator (see http://en.cppreference.com/w/cpp/concept/InputIterator) because they want to be able to increment and dereference the iterator. This has a very simple SFINAE solution in standard C++11, e.g. similar to that from the gcc STL:

    template
    using RequireInputIterator = typename
        std::enable_if::iterator_category,
                                           std::input_iterator_tag>::value>::type;
    
    ...
    
    // Example: declare a vector constructor from a pair of input iterators.
    template  >
        MyVector(InputIterator first, InputIterator last) { /* ... */ };
    

    This relies on the iterator type traits classes, which define the typedefs that Armen Tsirunyan thought were required of the iterators themselves. (The iterators can provide those typedefs, but they can also provide them in traits classes, which is necessary in order to use naked pointers as iterators, and the standard library implementations are required to do so.)

提交回复
热议问题