constexpr for loop compilation
Asked Answered
O

1

6

I have read this and but i still do not know how to make this work with -std=gnu++2a I am not sure how to use integer seq. Could you please help me with adapting the below code so that it compiles? Thx

constexpr bool example(const int k)
{
    return k < 23 ? true: false;
}

constexpr bool looper()
{
    constexpr bool result = false;
    for(int k = 0; k < 20; k ++)
    {
        for (int i = 0 ; i < k; ++i)
        {
        constexpr bool result = example(i);
        }
    }

    return result;
}

int main()
{
    constexpr bool result = looper();
    return 0;
}
Outfox answered 3/7, 2020 at 1:36 Comment(0)
L
3

constexpr is used with the vars known at the compile time like constexpr int i =1+2. The compiler can figure out the result before compiling and make it constant.

Here example(i);, this uses a non-constant variable and pass it to a function taking a const one, how do you expect this works?

And this return k < 23 ? true: false; can be written return k < 23 ;

If you want to make your loop work be done using index_sequence at compile-time, you can use something like the following

#include <utility>
#include <iostream>

template<size_t ...i>
constexpr bool example(std::index_sequence<i...>){
    return (false,..., (i < 23));
}

template< size_t...j>
constexpr bool helper(std::index_sequence<j...>)
{
    return ((example( std::make_index_sequence<j>{})),...);
}

template< size_t n>
constexpr bool loop()
{
    return helper(std::make_index_sequence<n>{});
}


int main()
{
    constexpr bool result = loop<20>();
    std::cout<<result;
    return 0;
}
Leitmotif answered 3/7, 2020 at 1:46 Comment(2)
I am actually trying to iterate over an integer sequence. but do not know how to generate it. If i knew how to do it, then i would call example(i)<sequence_number> or something similar. the k<23 is edited from a larger code base, but thank you for the comment. If you access the 2 links posted, it might become clearer what i am trying to do.Outfox
You don't even need result, you can just return (i<23),...;Contort

© 2022 - 2024 — McMap. All rights reserved.