最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c++ - How should I declare an interface function that gets a range of ints? - Stack Overflow

programmeradmin0浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论