Skip to content

Instantly share code, notes, and snippets.

@IvanVergiliev
Last active August 23, 2023 14:10
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save IvanVergiliev/9639530 to your computer and use it in GitHub Desktop.
Save IvanVergiliev/9639530 to your computer and use it in GitHub Desktop.
C++ Tuple implementation
#include <cstdio>
template<typename First, typename... Rest>
struct Tuple: public Tuple<Rest...> {
Tuple(First first, Rest... rest): Tuple<Rest...>(rest...), first(first) {}
First first;
};
template<typename First>
struct Tuple<First> {
Tuple(First first): first(first) {}
First first;
};
template<int index, typename First, typename... Rest>
struct GetImpl {
static auto value(const Tuple<First, Rest...>* t) -> decltype(GetImpl<index - 1, Rest...>::value(t)) {
return GetImpl<index - 1, Rest...>::value(t);
}
};
template<typename First, typename... Rest>
struct GetImpl<0, First, Rest...> {
static First value(const Tuple<First, Rest...>* t) {
return t->first;
}
};
template<int index, typename First, typename... Rest>
auto get(const Tuple<First, Rest...>& t) -> decltype(GetImpl<index, First, Rest...>::value(&t)) { //typename Type<index, First, Rest...>::value {
return GetImpl<index, First, Rest...>::value(&t);
}
int main() {
Tuple<int, int, double> c(3, 5, 1.1);
printf("%d\n", get<1>(c));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment