我正在构建一个网络协议,我想对我的消息结构使用静态多态性。
struct HelloConnectMessage {
void serialize(BinaryWriter &writer) const {
}
void deserialize(BinaryReader &reader) {
}
std::ostream &dump(std::ostream &o) const {
return o << "HelloConnectMessage()";
}
};
struct TestMessage {
boost::uint16_t foo;
void serialize(BinaryWriter &writer) const {
writer.writeUshort(foo);
}
void deserialize(BinaryReader &reader) {
foo = reader.readUshort();
}
std::ostream &dump(std::ostream &o) const {
return o << "TestMessage(foo=" << foo << ")";
}
};
每个消息都有一个唯一的标识符(id/opcode),我想将它们存储在一个映射中,并且能够在运行时执行它们,因为我知道它们没有任何基类。所以我想知道静态多态性是否可能。
也许这可以说明我的问题:
using opcode = std::uint16;
std::unordered_map<opcode, ?generic_type?> _protocol;
我想我能代替你吗?泛型类型?但这很复杂,因为我不能将模板放在类成员变量上。我也考虑了一个工厂,但我仍然有一个基本类型的问题。
template<class T>
std::unique_ptr<?generic_type?> messageFactory() {
return std::make_unique<T>();
}
std::unordered_map<opcode, std::unique_ptr<?generic_type?>(*)()> _protocol;
_protocol[1] = messageFactory<HelloConnectMessage>(); // example
如果没有父类,这是否最终可以实现我想要的功能?