Skip to content

Instantly share code, notes, and snippets.

@CTMacUser
Created April 2, 2013 04:04
Show Gist options
  • Save CTMacUser/5289842 to your computer and use it in GitHub Desktop.
Save CTMacUser/5289842 to your computer and use it in GitHub Desktop.
A custom literal suffix that returns an object that takes a function (object) for generic looping. C++11 required. The fact that the idea is theoretically and actually possible is amazing. I don't know if that's good or bad, yet.
/*
Copyright (C) 2013 by Daryle Walker
Based on posts off the Boost mailing lists on 2013-Jan-31 by Tim
Blechmann and TONGARI. C++11 is required; according to Live Work
Space's code-runner (on 2013-Apr-1), only Clang >= 3.2 and
GCC >= 4.7 accept it.
The original post (Tim Blechmann) of the 7 in the thread:
http://article.gmane.org/gmane.comp.lib.boost.devel/238310
The last one (TONGARI) had the user-defined literal idea:
http://article.gmane.org/gmane.comp.lib.boost.devel/238319
I'm placing this code on the Boost Software License.
*/
#include <cassert>
#include <utility>
class looper
{
unsigned long long int count_;
template < typename Function >
static
void loop( unsigned long long int count, Function &&function )
{ while ( count-- ) std::forward<Function>( function )(); }
public:
constexpr explicit
looper( unsigned long long int count )
: count_{ count }
{}
constexpr
auto repeat_count() const -> unsigned long long int
{ return count_; }
template < typename Function >
void operator ()( Function &&function ) const
{ loop(repeat_count(), std::forward<Function>( function )); }
};
inline constexpr
auto operator "" _times( unsigned long long int count ) -> looper
{ return looper{count}; }
int main( int, char *[] )
{
int i = 0;
assert( i == 0 );
10_times( [&i]{i += ( i + 1 );} );
assert( i == 1023 );
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment