5

Currently, I can compose ranges-v3 views like this:

auto v = ranges::view::reverse | ranges::view::filter([](int l){return l>5;});

But if I wanted to return v from a function I'd need to know its type. What is the type of a ranges-v3 view?

Piotr Skotnicki
  • 46,953
  • 7
  • 118
  • 160
dicroce
  • 45,396
  • 28
  • 101
  • 140

1 Answers1

6

Since C++14 you can use auto as the return type of functions and it will get deduced:

auto f() {
    return ranges::view::reverse | ranges::view::filter([](int l){return l>5;});
}
// f's return type is the type of the return expression, exactly as is I had:
// auto returnValue = return-expression;
// where f's type is decltype(returnValue)

The only downside is that the definition of f has to appear in the same TU where you are using it.

Rakete1111
  • 47,013
  • 16
  • 123
  • 162
  • I would say `auto const f() { ...` because the return value does not change. The only changing thing here is what the return value calculates lazily. – Patrick Fromberg Dec 04 '18 at 20:50
  • 2
    @PatrickFromberg No no no no you don't want that. You are right it doesn't change, but marking it as `const` inhibits move semantics and so the range will get copied instead of moved. I don't know how expensive that is, but a move is cheaper :) – Rakete1111 Dec 04 '18 at 21:31