C++ Logo

std-proposals

Advanced search

Re: "constexpr for" proposal

From: Gil Shallom <gil.shallom_at_[hidden]>
Date: Mon, 2 Nov 2020 12:16:45 -0800
On 31/10/2020 13:54, Ville Voutilainen wrote:
On Sat, 31 Oct 2020 at 21:19, Gil Shallom via Std-Proposals
<std-proposals_at_[hidden]> wrote:

Thank you, Peter, for the std::apply solution (https://en.cppreference.com/w/cpp/utility/apply#Example). It's very cool.
I agree with Marcin and Arthur that a "constexpr for" allows for an easier to read and more expressible code.
Anyone aware of a reason why p1306 did not include free form compile time for loops?
(It could get the compiler stuck - but so can any other template meta programming bug).
What do you mean by "free-form"? You can already have any for-loop you
like in a constexpr function,
those are "free-form".


Hi Ville, all,

I apologize for being grossly imprecise in my comment.

Of course, for loops are possible in constexpr functions.


I was merely wondering if "constexpr for" constructs such as below were already shot down as a bad idea, etc...

(because if I understand correctly, p1306 is similar but not exactly the same).


The code I was thinking of is something like printing every 2nd item in a tuple:

template <typename... Args>
std::ostream& print_tuple(std::ostream& os, const std::tuple<Args...>& t)
{
        for constexpr (std::size_t idx=0; idx<sizeof...(Args); idx+=2)
        {
                os << std::get<idx>(t) << (idx+1<sizeof...(Args) ?  "," : "");
        }
        return os;
}

or something like:

template <typename... Args>
std::ostream& print_tuple(std::ostream& os, const std::tuple<Args...>& t)
{
        for constexpr (std::size_t j=0; j<sizeof...(Args); ++j)
        {
                for constexpr (std::size_t idx=0; idx<sizeof...(Args); idx+=j)
                {
                        os << std::get<idx>(t) << (idx+1<sizeof...(Args) ?  "," : "");
                }
        }
        return os;
}

Thank you,

Gil



Received on 2020-11-02 14:16:48