Last active
August 29, 2015 14:19
-
-
Save if1live/bf8416d173417d903cd7 to your computer and use it in GitHub Desktop.
int list + car/cdr (c++ template metaprogramming)
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
/* | |
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