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

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

    In addition to the existing answers relying on SFINAE, a simpler approximation would be to simply define the function to take an arbitrary template type as the iterator:

    template 
    void function(Iter first, Iter last){
      Unit* val = *first;
    }
    

    This has a few downsides. Unlike the SFINAE solution (such as boost::enable_if), this doesn't give you exactly what you asked for. This compiles as long as an object of type Iter can be dereferenced yielding a value convertible to Unit*, which isn't quite the same thing. You have no guarantee that Iter is a completely STL-compliant iterator (it may just be another type which defines operator*), or that its value type is Unit* precisely.

    On the other hand, it's much simpler.

提交回复
热议问题