I want to pass a std::ranges::view
to a function which is an implementation of an interface, without creating a new vector
and allocating more memory.
virtual void doSomethingWithInts(std::ranges::input_range auto intsView) = 0;
Here is a more detailed example:
#include <ranges>
#include <algorithm>
class IGetRange{
virtual void doSomethingWithInts(std::ranges::input_range auto intsView) = 0;
};
class PrintRange : public IGetRange{
void doSomethingWithInts(std::ranges::input_range auto intsView) {
std::ranges::copy(intsView, std::cout);
}
};
class SendOverNetworkRange : public IGetRange{
NetworkAdapter networkAdapter;
void doSomethingWithInts(std::ranges::input_range auto intsView) {
//do some extra work with additional input
std::ranges::copy(intsView, networkAdapter);
}
};
class Caller {
std::vector<std::pair<int, std::string> pairs = {{1,"one"}, {2, "two"}};
std::unique_ptr<IGetRange> rngProcessor = std::makeUnique<SendOverNetworkRange>();
void sendKeys() {
auto passView = pairs | std::ranges::filter(...) | std::ranges::transform([](auto&& p) {return p.first;});
rngProcessor->doSomethingWithInts(passView);
}
};
But, it should be polymorphic, hence it is virtual
, and doesn't accept templates.
I don't want to pass a new vector
, because it will allocate more space. And a span
is not an option because I will have to allocate it.
I want to be able to pass just the range with a given type.