Define a 'for' loop macro in C++
#define loop(x,n) for(int x = 0; x < n; ++x)
In today's C++ we wouldn't use a macro for this, but we'd use templates and functors (which includes lambda's):
template<typename FUNCTION>
inline void loop(int n, FUNCTION f) {
for (int i = 0; i < n; ++i) {
f(i);
}
}
// ...
loop(5, [](int jj) { std::cout << "This is iteration #" << jj << std::endl; } );
The loop
function uses the variable i
internally, but the lambda doesn't see that. It's internal to loop
. Instead, the lambda defines an argument jj
and uses that name.
Instead of the lambda, you could also pass any function as long as it accepts a single integer argument. You could even pass std::to_string<int>
- not that loop
would do something useful with the resulting strings, but the syntax allows it.
[edit] Via Mathemagician; you can support non-copyable functors using
template<typename FUNCTION>
inline void loop(int n, FUNCTION&& f) {
for (int i = 0; i < n; ++i) {
std::forward<FUNCTION>(f)(i);
}
}
[edit] The 2020 variant, which should give better error messages when passing inappropriate functions.
inline void loop(int n, std::invocable<int> auto&& f) {
for (int i = 0; i < n; ++i) {
std::invoke(f,i);
}
}