如果我不想在下面的代码中调用
std::ranges::subrange
,而只想创建一个range
对象来保存稍后模板函数调用的结果,那么声明range
的正确方法是什么?
我想 decltype 应该在这里有所帮助,但我无法找出表示类型的方法。
推理
我只能在接下来的循环中为
range
提供第一个数据,并且我需要在循环结束后使用它,所以我需要这个对象在循环之外,而不是在开始时初始化。有时这很困难,甚至几乎不可能。
代码
#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();
}
您需要的类型是:
std::ranges::subrange<std::vector<int>::iterator>
,如图所示
#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>);
}