constexpr for 循环编译

euc*_*ian 5 c++ metaprogramming constexpr c++11 c++17

我已经读过这篇文章,但我仍然不知道如何使其工作,-std=gnu++2a 我不知道如何使用integer seq。您能帮我修改下面的代码以便它可以编译吗?谢谢

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;
}
Run Code Online (Sandbox Code Playgroud)

asm*_*mmo 3

constexpr与编译时已知的变量一起使用,例如constexpr int i =1+2. 编译器可以在编译之前计算出结果并使其恒定。

在这里example(i);,这使用了一个非常量变量并将其传递给一个采用const1 的函数,您期望它如何工作?

return k < 23 ? true: false;可以写成return k < 23 ;

index_sequence如果你想让你的循环工作在编译时完成,你可以使用类似下面的东西

#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;
}
Run Code Online (Sandbox Code Playgroud)