拆包的范围的元组到n元功能

时间:2019-02-01 17:46:14

标签: c++ range-v3

假设我有一系列元组,例如来自zip功能。难道这对操作范围的功能必须始终一元或确实存在一些改造其解压缩解析成函数的参数。基本上,我想执行以下操作:

  auto r1 = {1, 2, 3, 4};
  auto r2 = {'a', 'b', 'c', 'd'};
  auto chars = view::zip(r1, r2) | view::transform([](int a, char x) { return x; });

而不是显式使用std :: tie或std :: apply。

2 个答案:

答案 0 :(得分:1)

听起来您实际上需要的是爆炸元组参数的函数适配器。像这样(LIVE):

DOCUMENT_ROOT

,您可以将其范围表示为:

Sub PivotFilter()

  Dim wb As Workbook
  Dim ws As Worksheet
  Dim xDay As String
  Dim xDate As Date

  Set wb = ThisWorkbook
  Set ws = wb.Worksheets("Previous Day Open Pos")

  xDate = DateAdd("d", -1, Date)

  xDay = format(Date, "dddd")

  If xDay = "Monday" Then
     xDate = Date - 3
  Else
     xDate = Date - 1
  End If

  ThisWorkbook.Sheets("Previous Day Open POs").pivottables("PivotTable1") _ 
        .PivotFields("PO Creation Date").CurrentPage = "(All)"
  ws.pivottables("PivotTable1").PivotFields("PO Creation Date") _
        .PivotItem(xDate).Visible = True


End Sub

答案 1 :(得分:0)

不幸的是,似乎没有 transform-apply 视图。像其他答案一样简单的解决方案是调整您的 lambda,以便使用 std::apply(相当于 std::bind_front(std::apply<...>, your_lambda)

调用它
// C++20
template<typename F>
constexpr auto apply_to(F&& f) noexcept(noexcept([f=static_cast<F&&>(f)]{})) {
    return [f=static_cast<F&&>(f)]<typename Tuple>(Tuple&& tuple) noexcept(noexcept(::std::apply(f, static_cast<Tuple&&>(tuple)))) -> decltype(auto) {
        return ::std::apply(f, static_cast<Tuple&&>(tuple));
    };
}

// C++17
// (Or C++14 with another std::apply implementation, like ranges::tuple_apply)
template<typename F>
constexpr auto apply_to(F&& f) {
    return [f=static_cast<F&&>(f)](auto&& tuple) noexcept(noexcept(::std::apply(f, static_cast<decltype(tuple)&&>(tuple)))) -> decltype(auto) {
        return ::std::apply(f, static_cast<decltype(tuple)&&>(tuple));
    };
}

只需将您的 lambda 包装为 apply_to([](int a, char x) { /*...*/ })


或者,结构化绑定非常短(在 C++17 中)

    // Be careful about excessive copying. Fine for the simple
    // `std::tuple<char, int>`, but consider forwarding references
    auto chars = view::zip(r1, r2) | view::transform([](auto zipped) {
        auto [a, x] = zipped;
        return x;
    });