I am trying to write a general static_for
implementation that can accept bounds, an increment function & a comparison function to run a loop through. I have been using this construct with simple loops that increment by 1. In that case it is easy to stop the loop unrolling by simply specializing on the IDX & END
being equal.
However when the increment could be with an arbitrary integer, it is not guaranteed that the IDX & END
will always be equal. The if
conditional is only evaluated at run time. In the code snippet below I was trying to specialize on the std::false_type
which stops the recursion. The integral_constant is constructed by evaluating the std::less
functional (which could be substituted by the user for any other evaluation). Unfortunately this comparator
functional is also evaluated only at run time and therefore the compiler fails. Could someone advise on how to get this to work?
NOTE: Using C++11.
template <int idx, int end, typename eval, int count, typename comparator>
struct static_for_loop {
template <typename Lambda, typename... Args>
void operator()(const Lambda& function, Args... args) const {
if (comparator()(idx, end)) {
std::integral_constant<int, idx> i;
function(i, args...);
constexpr bool lesser = comparator()(idx + count, end);
static_for_loop<idx + count, end, std::integral_constant<bool, lesser>, count,
comparator>()(function, args...);
}
}
};
template <int idx, int end, int count, typename comparator>
struct static_for_loop<idx, end, std::false_type, count, comparator> {
template <typename Lambda, typename... Args>
void operator()(const Lambda& function, Args... args) const {}
};
template <int idx, int end, int count = 1, typename comparator = std::less<int>>
struct static_for {
template <typename Lambda, typename... Args>
void operator()(const Lambda& function, Args... args) const {
static_for_loop<idx, end, std::true_type, count, comparator>()(function, args...);
}
};