Skip to content

Instantly share code, notes, and snippets.

@dirocco
Created February 5, 2019 21:13
Show Gist options
  • Save dirocco/b6f56b1bf24c2c5a18f4453a23718f68 to your computer and use it in GitHub Desktop.
Save dirocco/b6f56b1bf24c2c5a18f4453a23718f68 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
print('''
#pragma once
#include <type_traits>
#include <tuple>
// Converts POD struct to std::tuple
// Autogenerated by totuple.py
// Adapted from https://www.reddit.com/r/cpp/comments/4yp7fv/c17_structured_bindings_convert_struct_to_a_tuple/
template <class T, class... TArgs> decltype(void(T{std::declval<TArgs>()...}), std::true_type{}) test_is_braces_constructible(int);
template <class, class...> std::false_type test_is_braces_constructible(...);
template <class T, class... TArgs> using is_braces_constructible = decltype(test_is_braces_constructible<T, TArgs...>(0));
struct any_type {
template<class T> constexpr operator T(); // non explicit
};
template<class T> auto to_tuple(T&& object) noexcept {
using type = std::decay_t<T>;
''')
elems = 20
for i in range(elems, 1, -1):
print(" %s if constexpr(is_braces_constructible<type, %s>{}) {" % ('' if i == elems else 'else', ', '.join(['any_type' for x in range(1,i)])))
plist = ', '.join(['p%d' % x for x in range(1,i)])
print(" auto&& [%s] = object;" % plist)
print(" return std::make_tuple(%s);" % plist)
print(" }")
print(" else { return std::make_tuple(); }")
print("}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment