Skip to content

Instantly share code, notes, and snippets.

@hsiuhsiu
Last active September 7, 2020 16:33
Show Gist options
  • Save hsiuhsiu/96c4196b06f8c7d05f06be7faee8e928 to your computer and use it in GitHub Desktop.
Save hsiuhsiu/96c4196b06f8c7d05f06be7faee8e928 to your computer and use it in GitHub Desktop.
C++ Tricks
// base case
template <class... Types, size_t n, size_t... indices>
std::tuple<Types...> toAnyTuple(
std::array<std::any, n> const& arr,
std::index_sequence<indices...>) {
return std::make_tuple(std::any_cast<Types&>(arr[indices])...);
}
// general case
template <
class... Types,
size_t n,
class = std::enable_if_t<(n == sizeof...(Types))>>
std::tuple<Types...> toAnyTuple(std::array<std::any, n> const& arr) {
return toAnyTuple<Types...>(arr, std::make_index_sequence<n>{});
}
std::tuple_cat;
std::any;
std::apply;
// Call funciton with parameters in Tuple
// Use the lambda wrapper to avoid calling non-static function directly.
// get type in C++
// https://stackoverflow.com/questions/28509273/get-types-of-c-function-parameters
template <class Tuple,
class T = std::decay_t<std::tuple_element_t<0, std::decay_t<Tuple>>>>
std::vector<T> to_vector(Tuple&& tuple)
{
return std::apply([](auto&&... elems) {
std::vector<T> result;
result.reserve(sizeof...(elems));
(result.push_back(std::forward<decltype(elems)>(elems)), ...);
return result;
}, std::forward<Tuple>(tuple));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment