[英]Passing std::ranges::views as parameters in C++20
I have a method that prints a list of integers (my actual method is a bit more complicated but it is also read-only):我有一个打印整数列表的方法(我的实际方法有点复杂,但它也是只读的):
void printElements(const std::vector<int> &integersList)
{
std::for_each(integersList.begin(), integersList.end(), [](const auto& e){
std::cout << e << "\n";
});
}
Now suppose I have the following vector:现在假设我有以下向量:
std::vector<int> vec{1,2,3,4,5,6,7,8,9,10};
Then I want to print even numbers only.然后我只想打印偶数。 To do this, I thought of employing the new
std::ranges
feature in C++20.为此,我想到了在 C++20 中使用新的
std::ranges
特性。 I know that you can do this as follows:我知道你可以这样做:
auto evenList = vec | std::views::filter([](auto i){ return i % 2 == 0; });
Now I would like to call printElements(evenList)
, however this obviously won't compile.现在我想调用
printElements(evenList)
,但这显然不会编译。 What would be the solution to this?解决方案是什么? Also can I write a single function that will both print a
std::vector
and an object of the same type as my evenList
?我还可以编写一个 function 来打印
std::vector
和与我的 evenList 相同类型的evenList
吗? Or do I need to write two separate functions?还是我需要编写两个单独的函数?
You can make printElements
take any object by making it a function template.您可以通过将 printElements 设置为 function 模板来使
printElements
采用任何 object。 This will instantiate it for views
as well as vector
s.这将为
views
和vector
实例化它。
#include <algorithm>
#include <iostream>
#include <ranges>
void printElements(std::ranges::input_range auto&& range) {
std::ranges::for_each(range, [](const auto& e) { std::cout << e << '\n'; });
}
or:或者:
// ...
#include <iterator>
void printElements(std::ranges::input_range auto&& range) {
using T = std::ranges::range_value_t<decltype(range)>;
std::ranges::copy(range, std::ostream_iterator<T>(std::cout, "\n"));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.