我已阅读 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;
}
最佳答案
constexpr
与编译时已知的变量一起使用,如 constexpr int i =1+2
.编译器可以在编译之前计算出结果并使其保持不变。
这里example(i);
,这使用一个非常量变量并将其传递给一个函数,该函数采用 const
一,你认为这如何运作?
还有这个 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;
}
关于c++ - constexpr for 循环编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62707246/