Last active
March 15, 2025 16:10
-
-
Save IvanVergiliev/9639530 to your computer and use it in GitHub Desktop.
C++ Tuple implementation
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
#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