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

前端 未结 5 1976
刺人心
刺人心 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:30

    Another way with templates is to trigger a static assertion if the condition is not met.

    #include 
    #include     
    #include 
    
    template 
    void foo(Iter from, Iter to)
    {
        BOOST_STATIC_ASSERT((boost::is_same::value_type, Type>::value));
        //...
    }
    
    int main()
    {
        int arr[10];
        foo(arr, arr + 10);    //OK
        foo(arr, arr + 10); //triggers static assertion
    }
    

    If you want to do away with templates, then it is also possible to write an "any_iterator" using type erasure. For example, like this on: http://stlab.adobe.com/classadobe_1_1any__iterator.html

提交回复
热议问题