【发布时间】:2018-12-03 19:33:35
【问题描述】:
目前,我可以像这样编写 range-v3 视图:
auto v = ranges::view::reverse | ranges::view::filter([](int l){return l>5;});
但如果我想从函数返回 v,我需要知道它的类型。 range-v3 视图的类型是什么?
【问题讨论】:
目前,我可以像这样编写 range-v3 视图:
auto v = ranges::view::reverse | ranges::view::filter([](int l){return l>5;});
但如果我想从函数返回 v,我需要知道它的类型。 range-v3 视图的类型是什么?
【问题讨论】:
从 C++14 开始,您可以使用 auto 作为函数的返回类型,它会被推导出来:
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)
唯一的缺点是f 的定义必须出现在您使用它的同一个 TU 中。
【讨论】:
auto const f() { ...,因为返回值不会改变。这里唯一改变的是返回值是惰性计算的。
const 会禁止移动语义,因此范围将被复制而不是移动。我不知道那有多贵,但搬家更便宜:)