Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/146.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用模板元编程展开for循环 如何编写一个简单的C++代码来简单地运行具有某个展开因子的for循环? 例如,我需要编写一个For循环,为数组的每个索引分配一个值I,即数组大小的a[I]=I,比如说1e6_C++_For Loop_Template Meta Programming - Fatal编程技术网

如何使用模板元编程展开for循环 如何编写一个简单的C++代码来简单地运行具有某个展开因子的for循环? 例如,我需要编写一个For循环,为数组的每个索引分配一个值I,即数组大小的a[I]=I,比如说1e6

如何使用模板元编程展开for循环 如何编写一个简单的C++代码来简单地运行具有某个展开因子的for循环? 例如,我需要编写一个For循环,为数组的每个索引分配一个值I,即数组大小的a[I]=I,比如说1e6,c++,for-loop,template-meta-programming,C++,For Loop,Template Meta Programming,现在我想添加一个展开因子,比如说20。我不想手动编写20行代码,然后迭代5k次。我该怎么做?我是否嵌套我的for循环?如果我使用模板元编程,编译器会自动为我展开吗?如何手动设置展开因子(当然是在编译时固定的)?下面的示例是用C++17编写的,但是使用一些更详细的技术,这个想法适用于C++11及更高版本 如果你真的想要强制展开,那么考虑和C++ 17的: #包括 #包括 #包括 名称空间详细信息{ 模板 constexpr void循环(std::integer_序列,F&&F){ (f(std:

现在我想添加一个展开因子,比如说20。我不想手动编写20行代码,然后迭代5k次。我该怎么做?我是否嵌套我的for循环?如果我使用模板元编程,编译器会自动为我展开吗?如何手动设置展开因子(当然是在编译时固定的)?

下面的示例是用C++17编写的,但是使用一些更详细的技术,这个想法适用于C++11及更高版本

如果你真的想要强制展开,那么考虑和C++ 17的:

#包括
#包括
#包括
名称空间详细信息{
模板
constexpr void循环(std::integer_序列,F&&F){
(f(std::integral_常量{}),…)//C++17次表达式
}
}//细部
模板
constexpr void循环(F&&F){
detail::loop(std::make_integer_sequence{},std::forward(f));
}
int main(){
循环([](自动i){
constexpr int它是偶数constexpr=i;

std::cout如果你不相信你的编译器能尽可能最好地展开,也许可以找到一个更好的编译器。重申n.m的答案,不要浪费时间假装自己是一个编译器。你的编译器知道如何最好地优化你的循环-包括展开的内容。省去在分析时发现瓶颈的修复工作。你可能会失败d这是有用的:
#include <iostream>
#include <type_traits>
#include <utility>

namespace detail {

template<class T, T... inds, class F>
constexpr void loop(std::integer_sequence<T, inds...>, F&& f) {
  (f(std::integral_constant<T, inds>{}), ...);// C++17 fold expression
}

}// detail

template<class T, T count, class F>
constexpr void loop(F&& f) {
  detail::loop(std::make_integer_sequence<T, count>{}, std::forward<F>(f));
}

int main() {
  loop<int, 5>([] (auto i) {
    constexpr int it_is_even_constexpr = i;
    std::cout << it_is_even_constexpr << std::endl;
  });
}