Home > Back-end >  Example of use of std::forward_iterator
Example of use of std::forward_iterator

Time:05-02

I have a compute function that looks like this:

template <typename PayloadType, complex ValueType>
         static void comupte_everything(
         const typename std::vector<DataPointWithAverage<PayloadType, ValueType>>::iterator begin,
         const typename std::vector<DataPointWithAverage<PayloadType, ValueType>>::iterator end)

I want to extend that function so it can accept any iterators instead of just vectors, and I'm trying to do it with std::forward_iterator:

template <typename PayloadType, complex ValueType,
std::forward_iterator<DataPointWithAverage<PayloadType, ValueType>> Iterator>
         static void comupte_everything(
          const Iterator begin,
          const Iterator end)

Now, the compiler complains that I give forward_iterator too many arguments.

How do I use this correctly?

CodePudding user response:

If you want an algorithm that iterates over a range of a specific type, defined by template parameters, then you should ask for that.

template typename PayloadType, complex ValueType, <std::forward_iterator It, std::sentinel_for<It> Sent>
    requires std::same_as<std::iter_value_t<It>, DataPointWithAverage<PayloadType, ValueType>>
  static void compute_everything(It start, Sent end)
{
}

CodePudding user response:

std::forward_iterator is a concept, not a template, so you can't use it like a template, if you want to constrain the value_type of iterator, then you can

template<typename T>
constexpr bool is_DataPointWithAverage = false;

template<typename PayloadType, complex ValueType>
constexpr bool is_DataPointWithAverage<
  DataPointWithAverage<PayloadType, ValueType>> = true;

template <std::forward_iterator I>
  requires is_DataPointWithAverage<std::iter_value_t<I>>
static void comupte_everything(I begin, I end);

which will constrain I must model forward_iterator, and its value_type must be a specialization of DataPointWithAverage.

Note that begin() and end() of a range in C 20 can return different types, so a more generic declaration should be

template <std::forward_iterator I, std::sentinel_for<I> S>
  requires is_DataPointWithAverage<std::iter_value_t<I>>
static void comupte_everything(I begin, S end);
  • Related