Function that takes an STL iterator over ANY container of a elements of a specific type

前端 未结 5 1977
刺人心
刺人心 2021-02-12 19:12

How would I define a function that takes as input an iterator over any type of STL container, but only to those of a specific templated type. For example:

Any iterator o

5条回答
  •  故里飘歌
    2021-02-12 19:41

    You could use a SFINAE construct such as boost::enable_if which verifies if the nested typedef iterator::value_type is indeed of the appropriate type.

    template
    typename boost::enable_if >::type
        f(Iterator i)
    {
        /* ... */
    }
    
    int main()
    {
        std::list l;
        std::vector v;
    
        f(l.begin()); // OK
        f(v.begin()); // OK
    
        std::vector v2;
        f(v2.begin()); /* Illegal */
    }
    

    This is what I understand from "a function that takes as input an iterator over any type of STL container, but only to those of a specific templated type", but my interpretation might be wrong.

提交回复
热议问题