Last active
September 7, 2020 16:33
-
-
Save hsiuhsiu/96c4196b06f8c7d05f06be7faee8e928 to your computer and use it in GitHub Desktop.
C++ Tricks
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
// 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>{}); | |
} |
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
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 |
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
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