Created
November 13, 2013 13:58
-
-
Save m-alvarez/7449539 to your computer and use it in GitHub Desktop.
Some C++ type-level fun
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <vector> | |
#include <iostream> | |
template<typename T, int i> | |
struct Conditional { | |
typedef T Type; | |
}; | |
template<typename T> | |
struct Conditional<T, 0>; | |
template<typename T, T l, T u> | |
struct Range { | |
template<T v> | |
struct Element { | |
static const typename Conditional<T, l <= v && v <= u>::Type value = v; | |
}; | |
}; | |
template<unsigned int i, typename T> | |
class Vec { | |
public: | |
unsigned int size() { return i; } | |
typedef Range<unsigned int, 0, i - 1> Indices; | |
template<unsigned int V> | |
T *deref() { | |
unsigned int index = Indices::template Element<V>::value; | |
return &v[ index ]; | |
} | |
void each(void (*fn)(unsigned int, T&)) { | |
unsigned int index = 0; | |
for (auto& elt : v) { | |
fn(index, elt); | |
index++; | |
} | |
} | |
void each(void (*fn)(T&)) { | |
for (auto elt : v) { | |
fn(elt); | |
} | |
} | |
void each(void (*fn)(T)) { | |
for (auto elt : v) { | |
fn(elt); | |
} | |
} | |
Vec(): v(std::vector<T>(i)) { | |
} | |
private: | |
std::vector<T> v; | |
}; | |
int main(void) { | |
Vec<5, int> v; | |
*v.deref<0>() = 10; | |
*v.deref<1>() = 11; | |
*v.deref<2>() = 12; | |
*v.deref<3>() = 13; | |
*v.deref<4>() = 14; | |
v.each( [](unsigned int i, int& x) { std::cout << i << ": " << x << std::endl; x++; } ); | |
v.each( [](int& x) { std::cout << x << std::endl; x++; } ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment