Skip to content

Instantly share code, notes, and snippets.

@hdon
Created December 18, 2014 04:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hdon/da3ce733c26651c1d340 to your computer and use it in GitHub Desktop.
Save hdon/da3ce733c26651c1d340 to your computer and use it in GitHub Desktop.
Compile-time linked list and key-value store
#include <iostream>
#include <type_traits>
using namespace std;
struct Nil {
typedef Nil Head;
typedef Nil Tail;
};
template <typename H, typename T = Nil> struct Lst {
typedef H Head;
typedef T Tail;
static const int Length = 1 + T::Length;
};
template <typename H> struct Lst <H, Nil> {
typedef H Head;
typedef Nil Tail;
static const int Length = 1;
};
template <typename L, int I> struct LstIndex {
typedef typename LstIndex<typename L::Tail, I-1>::Value Value;
};
template <typename L> struct LstIndex <L, 0> {
typedef typename L::Head Value;
};
template <int N> struct Int {
static const int value = N;
};
template <int K, int V> struct IntPair {
static const int key = K;
static const int value = V;
};
template <int QK, typename KVs> struct KeySearch :
conditional<KVs::Head::key == QK, typename KVs::Head, KeySearch<QK, typename KVs::Tail>>::type {};
template <int QK> struct KeySearch <QK, Nil> : Nil {};
typedef Lst< IntPair<4, 8>,
Lst< IntPair<6, 12>,
Lst< IntPair<1, 2>
>>> Foo;
int main(int argc, char** argv) {
cout << Foo::Length << ' '
<< Foo::Tail::Length << ' '
<< Foo::Tail::Tail::Length
<< endl;
cout << Foo::Head::key << ' '
<< Foo::Tail::Head::key << ' '
<< Foo::Tail::Tail::Head::key
<< endl;
cout << Foo::Head::value << ' '
<< Foo::Tail::Head::value << ' '
<< Foo::Tail::Tail::Head::value
<< endl;
cout << LstIndex<Foo, 0>::Value::value << ' '
<< LstIndex<Foo, 1>::Value::value << ' '
<< LstIndex<Foo, 2>::Value::value
<< endl;
cout << KeySearch<1, Foo>::value << ' '
<< KeySearch<4, Foo>::value << ' '
<< KeySearch<6, Foo>::value
<< endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment