【问题标题】:How to get type of a view?如何获取视图类型?
【发布时间】:2022-01-20 19:18:35
【问题描述】:

我想将视图的定义放在单独的编译单元中,但要导出视图,我需要它的类型。

// .h
auto GetView(int index, int size);
// .cpp
auto GetView(int index, int size)
{
    auto view = ranges::views::ints(-2, 3)
        | ranges::views::transform([=](auto i)
            {
                return i + index;
            }
        )
        | ranges::views::enumerate
        | ranges::views::filter([=](auto i)
            {
                return i.second >= 0 && i.second < size;
            }
        )
        ;
}

我将自己回答这个问题,但也许有人可以制作一些有用的 cmets。

【问题讨论】:

    标签: range-v3 std-ranges


    【解决方案1】:

    首先你可以从https://devblogs.microsoft.com/oldnewthing/20200528-00/使用whatis

    template<typename... Args> void whatis();
    auto GetView(int index, int size)
    {
        auto view = ...
            ;
        whatis<decltype>(view);
    }
    

    但是,我无法让给定类型的 lambda 工作

    • class `__cdecl GetView(int,int)'::`2'::&lt;lambda_1&gt;
    • class `__cdecl GetView(int,int)'::`2'::&lt;lambda_2&gt;

    所以我不得不将我的 lambda 封装在 std::function

    std::function<int(int)>([=](auto i)
                {
                    return i + index;
                })
    ...
    std::function<bool(std::pair<int,int>)>([=](auto i)
                {
                    return i.second >= 0 && i.second < size;
                })
    

    因此,编译器会告诉类型应该是:

    // .h
    struct ranges::filter_view<struct ranges::zip_view<struct ranges::detail::index_view<unsigned __int64, __int64>, struct ranges::transform_view<struct ranges::iota_view<int, int>, class std::function<int __cdecl(int)> > >, class std::function<bool __cdecl(struct std::pair<int, int>)> >
            GetView(int index, int size);
    

    【讨论】:

      【解决方案2】:

      您也可以使用ranges::any_view提供的类型擦除

      ranges::any_view<std::pair<int,int>>
      GetView2(int index, int size)
      {
          return ranges::views::ints(-2, 3)
              | ranges::views::transform([=](auto i)
                  {
                      return i + index;
                  }
              )
              | ranges::views::enumerate
              | ranges::views::filter([=](auto i)
                  {
                      return i.second >= 0 && i.second < size;
                  }
              )
              ;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-05-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-08
        • 1970-01-01
        相关资源
        最近更新 更多