Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to divide a tuple in C++

Tags:

c++

c++11

tuples

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;
}
like image 944
WangChu Avatar asked Aug 03 '17 07:08

WangChu


1 Answers

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.

like image 101
ecatmur Avatar answered Sep 21 '22 09:09

ecatmur