Assuming 10 is a compile-time constant ...
#include <cstddef> #include <utility> template<std::size_t N> struct do_N_times_type { template<typename Lambda> void operator()( Lambda&& closure ) const { closure(); do_N_times_type<N-1>()(std::forward<Lambda>(closure)); } }; template<> struct do_N_times_type<1> { template<typename Lambda> void operator()( Lambda&& closure ) const { std::forward<Lambda>(closure)(); } }; template<> struct do_N_times_type<0> { template<typename Lambda> void operator()( Lambda&& closure ) const { } }; template<std::size_t N, typename Lambda> void do_N_times( Lambda&& closure ) { do_N_times_type<N>()( std::forward<Lambda>(closure) ); }; #include <iostream> void f() { std::cout << "did it!\n"; } int main() { do_N_times<10>([&]{ f(); }); }
or simply
int main() { do_N_times<10>(f); }
Other funny methods:
Write a range iterator (I call my index ) that creates a range of types of iterators on the integral (by default I am std::size_t ). Then enter:
for( auto _:index_range(10) )
which uses the variable ( _ ) but looks extremely confusing.
Another crazy approach would be to create a generator like python. Writing a generator shell that takes an iterable range and creates a function that returns std::optional in the value_type range is not complicated.
Then we can:
auto _ = make_generator( index_range(10) ); while(_()) { }
which also creates a temporary variable and even dumber ones.
We could write a loop function that works with generators:
template<typename Generator, typename Lambda> void While( Generator&& g, Lambda&& l ) { while(true) { auto opt = g(); if (!opt) return; l(*opt); } }
which we then call:
While( make_generator( index_range(10) ), [&](auto&&){ f(); });
but this creates both temporary variables in the function and is more funny than the last ones, and relies on C ++ 1y functions that have not yet been finalized.
Those where my attempts to create a method without a variable to repeat something 10 times.
But actually, I would just do a loop.
You will almost certainly block the warning by typing x=x;
Or write a function
template<typename Unused> void unused( Unused&& ) {}
and call unused(x); - the variable x is used, and its name is entered inside, so the compiler may not warn you about this inside.
So try the following:
template<typename Unused> void unused( Unused&& ) {} for(int x{};x<10;++x) { unused(x); f(); }
which should suppress the warning, and really easy to understand.