对于一个C++程序,你可以在语言内部展开循环。你不需要找出编译器特定的选项。例如,
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;
}
使用闭包代替显式函数对象
int main(int argc, char* argv[])
{
int accumulator{3};
repeat<4>( [&](std::size_t)
{
accumulator += 2;
})();
std::cout << accumulator << std::endl;
}
__attribute__ ((hot))
可能值得一试。 - Brett Hale