Skip to content

Instantly share code, notes, and snippets.

@dagon666
Created November 30, 2014 12:21
Show Gist options
  • Save dagon666/6ea83dc483dbb9b1c791 to your computer and use it in GitHub Desktop.
Save dagon666/6ea83dc483dbb9b1c791 to your computer and use it in GitHub Desktop.
tuple
#include <iostream>
#include <type_traits>
template <typename ... > struct my_tuple {};
template <typename T, typename ... Ts>
struct my_tuple<T, Ts...> : my_tuple<Ts...> {
typedef T type;
type value;
my_tuple(T t, Ts ... ts) : value(t), my_tuple<Ts...>(ts...)
{
}
};
template <bool B, typename ... Ts>
using eit = std::enable_if_t<B, typename my_tuple<Ts...>::type>;
template <unsigned N, typename T, typename ... Ts >
eit<N!=0, Ts...> my_tuple_get(my_tuple<T,Ts...>& t) {
my_tuple<Ts...>& t2 = t;
return my_tuple_get<N - 1, Ts ... >(t2);
}
template <unsigned N, typename ... Ts >
eit<N==0, Ts...> my_tuple_get(my_tuple<Ts...>& t) {
return t.value;
}
int main(int argc, char *argv[])
{
my_tuple<int> mt1 {123};
my_tuple<int, std::string> mt2 {123, "test"};
std::cout << "mt1" << std::endl;
std::cout << my_tuple_get<0>(mt1) << std::endl;
std::cout << "mt2" << std::endl;
std::cout << my_tuple_get<0>(mt2) << std::endl;
std::cout << my_tuple_get<1>(mt2) << std::endl;
return 0;
}
$ g++ -std=c++14 my_tuple.cpp
$ ./a.out
mt1
123
mt2
123
test
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment