I have a question about dividing a tuple, as the title said.
In fact, I can do it using std::index_sequence
, but the code looks ugly.
Is there an elegant way of accomplishing this?
Here are some code to show what I mean.
#include<tuple>
using namespace std;
template<typename THead, typename ...TTails>
void foo(tuple<THead, TTails...> tpl)
{
tuple<THead> tpl_h { get<0>(tpl) };
tuple<TTails...> tpl_t { /* an elegent way? */ }
do_sth(tpl_h, tpl_t);
}
int main()
{
foo(make_tuple(1, 2.0f, 'c'));
return 0;
}
If you have a C++17-capable compiler, you can use apply
:
auto [tpl_h, tpl_t] = apply([](auto h, auto... t) {
return pair{tuple{h}, tuple{t...}};
}, tpl);
do_sth(tpl_h, tpl_t);
Example.
Since you're using VS2015.2, which supports C++14 and the later draft n4567, you're fairly restricted in the library support available. However, you can use piecewise_construct
:
struct unpacker {
tuple<THead> tpl_h;
tuple<TTails...> tpl_t;
unpacker(THead h, TTails... t) : tpl_h{h}, tpl_t{t...} {}
};
auto unpacked = pair<unpacker, int>{piecewise_construct, tpl, tie()}.first;
do_sth(unpacked.tpl_h, unpacked.tpl_t);
Example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With