C++ Logo

STD-PROPOSALS

Advanced search

Subject: Re: [std-proposals] count-based for loop
From: Barry Revzin (barry.revzin_at_[hidden])
Date: 2019-08-27 12:26:08


On Tue, Aug 27, 2019, 12:02 PM Sophia Poirier via Std-Proposals <
std-proposals_at_[hidden]> wrote:

> Thanks, yes I have that as an alternate example in my longer notes. My
> understanding is that it still suffers from the type-matching problem as
> traditional for loops. Your example of:
>
> for (const auto i : std::views::iota(0, count))
>
> only works when count is an int. Otherwise, if for example count is
> uint32_t, it would need to be:
>
> for (const auto i : std::views::iota(uint32_t{0}, count)
> or:
> for (const auto i : std::views::iota(0u, count))
> or:
> for (const auto i : std::views::iota<uint32_t>(0, count))
> or:
> for (const auto i : std::views::iota<decltype(count)>(0, count))
>
> or something along those lines, or you will get template instantiation
> failure compiler error. I think that if std::views::iota had a constructor
> overload that was simply the second argument (count) with implicit zero
> start, then it would be a good option. However I believe there is interest
> to reserve such an overload perhaps for infinite ranges?
>
> thanks,
> Sophia
>

This is true. But we can write a helper function to get the correct type of
0 so we don't need the ugliness at point of use:

template <std::integral T>
auto upto(T n) {
    return views::iota(T{0}, n);
}

We end up with:

for (const auto i : upto(count))

Barry

>



STD-PROPOSALS list run by herb.sutter at gmail.com

Standard Proposals Archives on Google Groups