Skip to content

Instantly share code, notes, and snippets.

@ph1ee
Last active August 29, 2015 14:26
Show Gist options
  • Select an option

  • Save ph1ee/691ba86c9550fa747e12 to your computer and use it in GitHub Desktop.

Select an option

Save ph1ee/691ba86c9550fa747e12 to your computer and use it in GitHub Desktop.
Loop Unrolling in C++ TMP
// Generative Programming: Methods, Techniques and Applications
// Ch.8 Static Metaprogramming in C++
#include <iostream>
using namespace std;
template <int i>
struct aStatement {
enum { n = i };
static void exec() { cout << i << endl; }
typedef aStatement<n + 1> Next;
};
struct aCondition {
template <class Statement>
struct Code {
enum { RET = (Statement::n <= 10) };
};
};
template <bool condition, class Then, class Else>
struct IF {
typedef Then RET;
};
// partial specialization
template <class Then, class Else>
struct IF<false, Then, Else> {
typedef Else RET;
};
struct Stop {
static void exec(){};
};
template <class Condition, class Statement>
struct WHILE {
static void exec() {
IF<Condition::template Code<Statement>::RET, Statement, Stop>::RET::exec();
typedef typename Statement::Next NewStatement;
IF<Condition::template Code<Statement>::RET, WHILE<Condition, NewStatement>,
Stop>::RET::exec();
}
};
int main() { WHILE<aCondition, aStatement<1>>::exec(); }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment