【问题标题】:How to divide a tuple in C++如何在 C++ 中划分元组
【发布时间】:2017-08-03 07:59:54
【问题描述】:

正如标题所说,我有一个关于划分元组的问题。

其实我可以用std::index_sequence来做,但是代码看起来很难看。

有没有优雅的方法来完成这个?

这里有一些代码来说明我的意思。

#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;
}

【问题讨论】:

标签: c++ c++11 tuples


【解决方案1】:

如果你有支持 C++17 的编译器,你可以使用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.

由于您使用的是 VS2015.2,它支持 C++14 和更高版本的草案 n4567,因此您在可用的库支持方面受到了相当大的限制。不过,你可以使用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.

【讨论】:

  • 谢谢。但我使用的是 VS2015.2(支持 C++ 14)。有没有不用更换编译器就可以使用的方法?
  • @WangChu: apply可以用C++14实现。
  • @Jarod42 好的,我会试试的。
  • @WangChu 找到了使用piecewise_construct 的 C++14 解决方案,但它的优雅程度要低得多。
猜你喜欢
  • 1970-01-01
  • 2016-04-23
  • 2016-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-23
  • 2017-06-30
  • 1970-01-01
相关资源
最近更新 更多