对于 C++ 程序,您可以在语言中展开循环。您无需弄清楚特定于编译器的选项。例如,
#include <cstddef>
#include <iostream>
template<std::size_t N, typename FunctionType, std::size_t I>
class repeat_t
{
public:
repeat_t(FunctionType function) : function_(function) {}
FunctionType operator()()
{
function_(I);
return repeat_t<N,FunctionType,I+1>(function_)();
}
private:
FunctionType function_;
};
template<std::size_t N, typename FunctionType>
class repeat_t<N,FunctionType,N>
{
public:
repeat_t(FunctionType function) : function_(function) {}
FunctionType operator()() { return function_; }
private:
FunctionType function_;
};
template<std::size_t N, typename FunctionType>
repeat_t<N,FunctionType,0> repeat(FunctionType function)
{
return repeat_t<N,FunctionType,0>(function);
}
void loop_function(std::size_t index)
{
std::cout << index << std::endl;
}
int main(int argc, char** argv)
{
repeat<10>(loop_function)();
return 0;
}
具有复杂循环功能的示例
template<typename T, T V1>
struct sum_t
{
sum_t(T v2) : v2_(v2) {}
void operator()(std::size_t) { v2_ += V1; }
T result() const { return v2_; }
private:
T v2_;
};
int main(int argc, char* argv[])
{
typedef sum_t<int,2> add_two;
std::cout << repeat<4>(add_two(3))().result() << std::endl;
return 0;
}
// output is 11 (3+2+2+2+2)
使用闭包而不是显式函数对象
int main(int argc, char* argv[])
{
int accumulator{3};
repeat<4>( [&](std::size_t)
{
accumulator += 2;
})();
std::cout << accumulator << std::endl;
}