Skip to content

Instantly share code, notes, and snippets.

@sekia
Created October 6, 2016 15:42
Show Gist options
  • Select an option

  • Save sekia/16fbd085098253a3c91e1b5b7bf0e77a to your computer and use it in GitHub Desktop.

Select an option

Save sekia/16fbd085098253a3c91e1b5b7bf0e77a to your computer and use it in GitHub Desktop.
Parameter pack excercise
#include <cstddef>
using namespace std;
template <size_t N, typename Car, typename Cdr>
struct Nth {
static_assert(N > 0, "Index out of range.");
using Type = typename Cdr::template Nth<N - 1>::Type;
};
template <typename Car, typename Cdr>
struct Nth<1, Car, Cdr> { using Type = Car; };
template <typename ...Types>
struct TypeList {
template <typename Kar, typename ...Kdr>
struct TypeList1 {
using Car = Kar;
using Cdr = TypeList<Kdr...>;
};
using Car = typename TypeList1<Types...>::Car;
using Cdr = typename TypeList1<Types...>::Cdr;
constexpr static bool IsNull = false;
constexpr static size_t Size = 1 + Cdr::Size;
template <size_t N>
using Nth = Nth<N, Car, Cdr>;
};
template <>
struct TypeList<> {
using Car = void;
using Cdr = void;
constexpr static bool IsNull = true;
constexpr static size_t Size = 0;
template <size_t N>
struct Nth { using Type = void; };
};
#include <iostream>
int main(int, char **) {
using TypeList = TypeList<int, double>;
TypeList::Nth<1>::Type v = 42;
TypeList::Nth<2>::Type u = 3.14;
cout << TypeList::Size << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment