Home > Net >  How to get the type of the values in a C 20 std::ranges range?
How to get the type of the values in a C 20 std::ranges range?

Time:11-19

Given a std::ranges::range in C 20, how can I determine the type of the values in that range?

I want to write a function that makes a std::vector out of an arbitrary range. I'd like this function to have a nice, explicit declaration. Something like:

template<std::ranges::range Range>
std::vector<std::value_type_t<Range>> make_vector(Range const&);

The following seems to work, but the declaration is not explicit and the implementation is ugly (even ignoring that it doesn't allocate the right size up-front where possible).

  template<std::ranges::range Range>
  auto make_vector(Range const& range)
  {
    using IteratorType = decltype(std::ranges::begin(std::declval<Range&>()));
    using DerefType    = decltype(*std::declval<IteratorType>());
    using T            = std::remove_cvref_t<DerefType>;
    std::vector<T> retval;
    for (auto const& x: range) {
      retval.push_back(x);
    }
    return retval;
  }

Is there a canonical/better/shorter/nicer way to do this?

CodePudding user response:

The type trait you are looking for is spelled std::ranges::range_value_t, not std::value_type_t.

Also, the whole function you are trying to write here is just a more limited version of std::ranges::to coming in C 23.

  • Related