I think this one basically has to be recursive. There is no such thing in the standard library, and for once I can't come up with a Boost.Mp11 one-liner.
namespace impl {
template <typename T>
struct unfold_t {
using type = std::tuple<T>;
};
template <typename A, typename B>
struct unfold_t<std::pair<A, B>> {
using type = mp_push_back<typename unfold_t<A>::type, B>;
};
}
template <typename T>
using unfold = typename impl::unfold_t<T>::type;
With an assist from T.C., the newest edition of Mp11 (1.73) has an algorithm named mp_iterate
which we can use thusly.
Given std::pair<std::pair<X, Y>, Z>
, if we apply mp_first
repeatedly (as R
) we get the sequence:
std::pair<std::pair<X, Y>, Z>
std::pair<X, Y>
X
Then, if we apply mp_second
to that sequence, we get:
That's pretty close. We do need that X
. So we need a more complex metafunction for F
: we need to get the second value if possible. There's a metafunction for that:
template <typename L>
using second_or_self = mp_eval_or<L, mp_second, L>;
And now mp_iterate<T, second_or_self, mp_first>
gives us mp_list<Z, Y, X>
. All we need to do at that point is reverse it and turn it into a std::tuple
:
template <typename L>
using unfold = mp_rename<mp_reverse<
mp_iterate<L, second_or_self, mp_first>>,
std::tuple>;
Now that Boost.173 is on compiler-explorer, demo.
Or, I suppose, if you really hate your readers, you can make this a single alias:
template <typename L>
using unfold = mp_rename<mp_reverse<
mp_iterate_q<L,
mp_bind<mp_eval_or_q, _1, mp_quote<mp_second>, _1>,
mp_quote<mp_first>>>,
std::tuple>;
pair<pair<a, b>, c>
intotuple<a, b, c>
? That doesn't seem like a "fold" to me - more like an unfold. – Barry May 1 '20 at 14:13