简体   繁体   中英

Alternative to virtual template methods in C++

Suppose that you have an abstract template class IParser that has a virtual method called parse that should parse a string and return an object of template type.

You have another abstract class INetlinkAdapter that is representing an adapter for Netlink communication ad it provides a virtual method to send a request and parse its reply using an IParser .

So something like the following:

template<typename T>
struct IParser<T> {
   std::shared_ptr<T> parse(std::string_view message) const;
};

struct INetlinkAdapter {
   template<typename T>
   virtual std::shared_ptr<T> sendRequestAndParseReply(int request, const IParser<T> & replyPparser);
};

This would be invalid since it is not possible to have virtual template methods in C++.

So I was wondering which could be an elegant and robust solution for this architectural problem.

The first thing I do in these situations is I forget the C++ object model exists. Pretend there is no virtual .

C++ remains a full featured OO language without it, you just have to do inheritance the C way.

Our parser is just a function from bytes to an object instance. (The shared ptr requirement is implementation leak).

The.network link adapter takes a request, produces bytes, then feeds it to the parser, which produces the object instance.

At this point you should see we are doing composition of functions.

So we rewrite our code to know this.

struct bytes; // some stream of bytes 
template<class T>
using parser=std::function<std::shared_ptr<T>(bytes)>;

struct request;

using ByteProvider=std::function<bytes(request)>;

tenplate<class T>
using DataProvider=std::function<std::shared_ptr<T>(request)>;

template<class T>
DataProvider<T> GetDataProvider(ByteProvider b, Parser<T> p){
  return [=](request r)){
    return p(b(r));
  };
}

We can rewrite this OO style by having a template method that does the bytes-to-parser in the interface, and pure virtual methods that do the bytes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM