-1

I want put the definition of a view in a separate compilation unit, but to export the view I need it's type.

// .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;
            }
        )
        ;
}

I'm going to answer this one myself but maybe someone can make some helpful comments.

Tom Huntington
  • 2,260
  • 10
  • 20

2 Answers2

0

First you can use whatis from https://devblogs.microsoft.com/oldnewthing/20200528-00/

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

However, I could not get the given type of the lambdas to work

  • class `__cdecl GetView(int,int)'::`2'::<lambda_1>
  • class `__cdecl GetView(int,int)'::`2'::<lambda_2>

So I had to wrap my lambdas in 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;
            })

Thus, the compiler will tell the type should be:

// .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);
Tom Huntington
  • 2,260
  • 10
  • 20
0

Alternatively you can use type erasure provided by 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;
            }
        )
        ;
}
Tom Huntington
  • 2,260
  • 10
  • 20