我正在尝试为PacketDecoder创建一个非模板基类,因此我可以将Base*存储在std :: map中.解码功能正在被正确覆盖.编码功能给我这个错误"'编码'不是虚拟的,不能声明为纯".我可能会考虑来自Java背景的这个问题.是否有更惯用的c ++方法解决这个问题?
class Base {
public:
virtual Packet* decode(folly::io::Cursor& cursor) = 0;
virtual void encode(Packet* packet) = 0;
};
template<typename T, typename std::enable_if<std::is_base_of<Packet, T>::value>::type* = nullptr>
class PacketDecoder : public Base {
public:
virtual T* decode(folly::io::Cursor& cursor) = 0;
virtual void encode(T *packet) = 0;
};
Run Code Online (Sandbox Code Playgroud)
用法示例:
class TestDecoder : public PacketDecoder<ProxyJoinPacket> {
public:
ProxyJoinPacket *decode(folly::io::Cursor &cursor) override {
uint32_t stringLength;
if (!cursor.tryReadBE<uint32_t>(stringLength)) {
throw std::runtime_error("Failed to read string length");
}
if (cursor.length() < stringLength) {
throw std::runtime_error("Too …Run Code Online (Sandbox Code Playgroud)