Search code examples
c++iteratorc++-conceptsc++23

Which concept to use for checking an iterator's value type?


I'm new to concepts and ranges/views.

I'm trying to write the initialization of a class by passing a sequence of values defined by an iterator or by a range/view.

I'm able to check that the function arguments are iterators or ranges. But I can't check that the values returned by the iterators are a specific type.

For example (C++23):

#include <print>
#include <vector>

struct Data {
    int i;
    std::string l;
};

struct DataContainer {
    // iterator version
    // QUESTION: how can I check that I handles "Data"?
    template<std::input_iterator I, std::sentinel_for<I> S>
    void add(I start, S end) {
        for (auto data = start; data != end; ++data) {
            _data.push_back(*data);
        }
    }
    // range/views version
    // QUESTION: how can I check that R handles "Data"?
    template<std::ranges::input_range R>
    void add(R &&r) {
        add(std::begin(r), std::end(r));
    }
    void dump() const {
        for (const auto& d: _data){
            std::print("[{},'{}'], ", d.i, d.l);
        }
        std::println();
    }
    std::vector<Data> _data;
};

int main()
{
    std::vector<Data> init{{1, "one"}, {2, "two"}, {3, "three"}};
    {
        DataContainer dc;
        dc.add(init.begin(), init.end());
        dc.dump();
    }
    {
        DataContainer dc;
        dc.add(init);
        dc.dump();
    }
    return 0;
}

How can I check that *start returns a Data?


Solution

  • In both cases you could add a constraint:

    template <std::input_iterator I, std::sentinel_for<I> S>
        requires std::convertible_to<std::iter_value_t<I>, Data> // constraint added
    void add(I start, S end) {
        // ...
    }
    
    template <std::ranges::input_range R>
        requires std::convertible_to<std::ranges::range_value_t<R>, Data> // constraint added
    void add(R&& r) {
        // ...
    }
    

    std::convertible_to:

    The concept convertible_to<From, To> specifies that an expression of the same type and value category as those of std::declval<From>() can be implicitly and explicitly converted to the type To, and the two forms of conversion produce equal results.

    std::iter_value_t

    1. Computes the value type of T.
    • If std::iterator_traits<std::remove_cvref_t<T>> is not specialized, then std::iter_value_t<T> is std::indirectly_readable_traits<std::remove_cvref_t<T>>::value_type.
    • Otherwise, it is std::iterator_traits<std::remove_cvref_t<T>>::value_type.

    std::ranges::range_value_t:

    Used to obtain the value type of the iterator type of range type R.

    A more relaxed version could use std::constructible_from instead of std::convertible_to.