Skip to content

Instantly share code, notes, and snippets.

@if1live
Last active August 29, 2015 14:19
Show Gist options
  • Save if1live/bf8416d173417d903cd7 to your computer and use it in GitHub Desktop.
Save if1live/bf8416d173417d903cd7 to your computer and use it in GitHub Desktop.
int list + car/cdr (c++ template metaprogramming)
/*
type list를 참조해서 만든 int list와 car, cdr
reference : http://coliru.stacked-crooked.com/a/0af9789bed2adaf7
*/
#include <type_traits>
#include <climits>
template<int... Items>
struct intlist;
template<typename intlist>
struct car;
template<int Head, int... Remainder>
struct car < intlist<Head, Remainder...> > {
enum {
value = Head
};
};
template<>
struct car < intlist<> > {
enum {
value = INT_MAX
};
};
static_assert(car<intlist<1, 2, 3>>::value == 1, "");
static_assert(car<intlist<>>::value == INT_MAX, "");
template<typename intlist>
struct cdr;
template<int Head, int... Remainder>
struct cdr < intlist<Head, Remainder...> > {
typedef intlist<Remainder...> value;
};
template<int Head>
struct cdr < intlist<Head> > {
typedef intlist<> value;
};
static_assert(car<cdr<intlist<1, 2, 3>>::value>::value == 2, "");
static_assert(car<intlist<1>>::value == 1, "");
static_assert(std::is_same<cdr<intlist<1>>::value, intlist<>>::value == 1, "");
static_assert(car<intlist<1, 2, 3>>::value == 1, "");
static_assert(car<cdr<intlist<1, 2, 3>>::value>::value == 2, "");
static_assert(car<cdr<cdr<intlist<1, 2, 3>>::value>::value>::value == 3, "");
static_assert(car<cdr<cdr<cdr<intlist<1, 2, 3>>::value>::value>::value>::value == INT_MAX, "");
int main() {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment