【问题标题】:constexpr for loop compilation用于循环编译的 constexpr
【发布时间】:2020-10-23 16:42:42
【问题描述】:

我已阅读 this,但我仍然不知道如何使用 -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;
}

【问题讨论】:

    标签: c++ c++11 c++17 metaprogramming constexpr


    【解决方案1】:

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

    这里example(i);,它使用一个非常量变量并将其传递给一个采用const 的函数,你认为它是如何工作的?

    而这个return k &lt; 23 ? true: false;可以写成return k &lt; 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;
    }
    

    【讨论】:

    • 我实际上是在尝试迭代一个整数序列。但不知道如何生成它。如果我知道该怎么做,那么我会调用 example(i) 或类似的东西。 k
    • 你甚至不需要result,你可以只需要return (i&lt;23),...;
    猜你喜欢
    • 2020-02-10
    • 1970-01-01
    • 1970-01-01
    • 2017-03-09
    • 1970-01-01
    • 2012-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多