Skip to content

Instantly share code, notes, and snippets.

@ueokande
Created April 22, 2015 13:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ueokande/e7c7cf45c26b1e79cf27 to your computer and use it in GitHub Desktop.
Save ueokande/e7c7cf45c26b1e79cf27 to your computer and use it in GitHub Desktop.
C++ tuple utils
#include <tuple>
#include <iostream>
template <typename Tuple, size_t ...xs>
constexpr auto sub_tuple(const Tuple &t, std::index_sequence<xs...>) {
return std::make_tuple(std::get<xs>(t)...);
}
template <typename Tuple, size_t x, size_t ...xs>
constexpr auto sub_tail_tuple(const Tuple &t, std::index_sequence<x, xs...>) {
return std::make_tuple(std::get<xs>(t)...);
}
template <typename Tuple>
constexpr auto tuple_head(const Tuple &t) {
return std::get<0>(t);
}
template <typename Tuple>
constexpr auto tuple_last(const Tuple &t) {
return std::get<std::tuple_size<Tuple>::value - 1>(t);
}
template <typename Tuple>
constexpr auto tuple_init(const Tuple &t) {
constexpr size_t tuple_size = std::tuple_size<Tuple>::value;
return sub_tuple(t, std::make_index_sequence<tuple_size - 1>());
}
template <typename Tuple>
constexpr auto tuple_tail(const Tuple &t) {
constexpr size_t tuple_size = std::tuple_size<Tuple>::value;
return sub_tail_tuple(t, std::make_index_sequence<tuple_size>());
}
int main() {
std::tuple<int, double, std::string> tuple(1, 2.0, "abc");
auto head = tuple_head(tuple);
auto last = tuple_last(tuple);
auto init = tuple_init(tuple);
auto tail = tuple_tail(tuple);
std::cout << "head : " << head << std::endl;
std::cout << "last : " << last << std::endl;
std::cout << "init : " << std::get<0>(init) << ", " << std::get<1>(init) << std::endl;
std::cout << "tail : " << std::get<0>(tail) << ", " << std::get<1>(tail) << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment