lundi 26 juin 2017

Is c++ STL template parameter precise enough?

For example, c++ std::find_if is implemented like:

template <class InputIter, class UnaryPredicate>
InputIter find_if(InputIter begin, InputIter end, UnaryPredicate pred) {
    for (; begin != end; begin++) {
        if (pred(*begin))
            return begin;
    }
    return end;
}

  • InputIter should be std::input_iterator_tag type, but in this function, any type which has operator++ operator++(int) can be compiled.
  • UnaryPredicate should be something like bool function(const T &value), but any function return int double can be compiled.

Is STL template parameter precise enough ? It seems doesn't check all possible error when compiling.

Can we implement it like:

template <T, Iter<? super std::input_iterator<T>>, Pred<? implement bool (const T&)>>
Iter find_if(Iter begin, Iter end, Pred p) {
  for (; begin != end; begin++) {
    if (p(*begin))
      return begin;
  }
  return end;
}

In this fake code, I want find_if work for type T, it has range in [begin, end), and use bool (const T &) to check if it is statisfied ?

Aucun commentaire:

Enregistrer un commentaire