gpt4 book ai didi

c++ - for 语句中的 constexpr

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:57:26 24 4
gpt4 key购买 nike

提供 if constexpr ,其中:

the value of condition must be a contextually converted constant expression of type bool. If the value is true, then statement-false is discarded (if present), otherwise, statement-true is discarded

有没有办法在 for 语句中也使用它?要在编译时展开循环?我希望能够做这样的事情:

template <int T>
void foo() {
for constexpr (auto i = 0; i < T; ++i) cout << i << endl;
}

最佳答案

Is there a way to use this in a for-statement as well? To unroll a loop at compile time? Id like to be able to do something like this

我不这么想。

但如果你能负担得起辅助函数,使用 std::integer_sequence 和未使用的 C 风格整数数组的初始化,从 C++14 开始,你可以执行以下操作

#include <utility>
#include <iostream>

template <int ... Is>
void foo_helper (std::integer_sequence<int, Is...> const &)
{
using unused = int[];

(void)unused { 0, (std::cout << Is << std::endl, 0)... };
}

template <int T>
void foo ()
{ foo_helper(std::make_integer_sequence<int, T>{}); }

int main ()
{
foo<42>();
}

如果可以使用C++17,就可以避免unused数组,使用折叠,foo_helper()可以简单的写成如下

template <int ... Is>
void foo_helper (std::integer_sequence<int, Is...> const &)
{ ((std::cout << Is << std::endl), ...); }

关于c++ - for 语句中的 constexpr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48913092/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com