How to restrict an iterator to being a forward iterator?

后端 未结 4 2017
终归单人心
终归单人心 2021-02-09 16:38

I have a function that needs to enumerate an iterator multiple times, but according to MSDN, \"Once you increment any copy of an input iterator, none of the other copies can

4条回答
  •  醉话见心
    2021-02-09 17:08

    To expand on rodrigo's answer -- I found this solution, and thought it's worth mentioning:

    struct True { unsigned char _[2]; operator bool() const { return true; } };
    char is_forward_iterator(std::input_iterator_tag const *) { return 0; }
    True is_forward_iterator(std::forward_iterator_tag const *) { return True(); }
    

    Now, if you want to check it inside some function, you can say:

    if (is_forward_iterator(static_cast::iterator_category*>(0)))
    {
        ...
    }
    

    and if you want to check it within templates, you can check for:

    sizeof(
      is_forward_iterator(static_cast::iterator_category*>(0))
    ) > 1
    

    with the primary advantage of this method being that it avoids declaring templates (e.g. for better compilation speed).

提交回复
热议问题