In case I don’t want to call the std::ranges::subrange
in the code below and want only to create a range
object which will hold the results of the template function call later, what is the correct way to declare range
?
I guess decltype should help here, but I can’t figure out the way to represent the type.
Reasoning
I will be able to provide first data for range
only in the loop which will follow and I will need to use it after the loop ends, so I need this object outside the loop and not initialized at the beginning. Sometimes this is hard or even next to impossible.
The code
#include <ranges>
#include <vector>
int main()
{
std::vector<int> values(10);
// How to replace this with default initialization for range based on type only,
// without the call to std::ranges::subrange ?
auto range = std::ranges::subrange(values.begin(), values.end());
while (...) {
range = std::ranges::equal_range(...);
}
size_t last_range_size = range.size();
}
The type you need is : std::ranges::subrange<std::vector<int>::iterator>
as shown here
#include <ranges>
#include <vector>
#include <type_traits>
int main()
{
std::vector<int> values(10);
// How to replace this with default initialization for range based on type only,
// without the call to std::ranges::subrange ?
auto range = std::ranges::subrange(values.begin(), values.end());
// From https://en.cppreference.com/w/cpp/ranges/subrange
// it follows this is the type :
using range_t = std::ranges::subrange<std::vector<int>::iterator>;
// And this verifies the type equality
static_assert(std::is_same_v<decltype(range),range_t>);
}