Created
January 14, 2014 12:02
-
-
Save DieHertz/8417266 to your computer and use it in GitHub Desktop.
C++11 typelists
This file contains hidden or 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
struct NullType {}; | |
template <typename T, typename U> | |
struct TypeList { | |
using Head = T; | |
using Tail = U; | |
}; | |
template <typename...> struct MakeTypeList; | |
template <> | |
struct MakeTypeList<> { | |
using Result = NullType; | |
}; | |
template <typename Head, typename... Types> | |
struct MakeTypeList<Head, Types...> { | |
using Result = TypeList<Head, typename MakeTypeList<Types...>::Result>; | |
}; | |
/** | |
*/ | |
template <typename> struct Length; | |
template <> | |
struct Length<NullType> { | |
enum { value = 0 }; | |
}; | |
template <typename Head, typename Tail> | |
struct Length<TypeList<Head, Tail>> { | |
enum { value = Length<Tail>::value + 1 }; | |
}; | |
/** | |
*/ | |
template <typename, typename> struct IndexOf; | |
template <typename T> | |
struct IndexOf<NullType, T> { | |
enum { value = -1 }; | |
}; | |
template <typename T, typename Tail> | |
struct IndexOf<TypeList<T, Tail>, T> { | |
enum { value = 0 }; | |
}; | |
template <typename Head, typename Tail, typename T> | |
struct IndexOf<TypeList<Head, Tail>, T> { | |
using Result = IndexOf<Tail, T>; | |
enum { value = Result::value == -1 ? -1 : Result::value + 1 }; | |
}; | |
#include <iostream> | |
int main() { | |
using IntTypes = typename MakeTypeList<char, bool, void>::Result; | |
std::cout << "Length<> : " << Length<IntTypes>::value << '\n'; | |
std::cout << "IndexOf<char> : " << IndexOf<IntTypes, char>::value << '\n'; | |
std::cout << "IndexOf<bool> : " << IndexOf<IntTypes, bool>::value << '\n'; | |
std::cout << "IndexOf<int> : " << IndexOf<IntTypes, int>::value << '\n'; | |
std::cout << "IndexOf<void> : " << IndexOf<IntTypes, void>::value << '\n'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment