如何避免使用类型名称类型
How can I avoid using the type name type
我的基类中有一个声明:
template<class PROTOCOL>
static Packet* serialize(uint packetId, QVariantHash data = QVariantHash());
然后,当我从基类继承时,我可以使用这样的静态方法:
GameProtocol::serialize<GameProtocol>(0); // This works fine
我的问题是,为了使调用GameProtocol::serialize(0)
工作(即,不使用模板声明),我必须更改什么。
我希望该方法保持静态,因为它简化了基类的其他区域。我知道这会让它变得困难,因为C++中不能重写静态方法,但肯定有一种方法可以使用模板魔术。
似乎GameProtocol
恰好是您的派生类:只需添加一个static
方法serialize()
,该方法将转发到基类的适当版本:
class GameProtocol: public Protocol {
// ...
public:
static Packet* serialize(uint id,
QVariantHash h = QVariantHash()) {
return Protocol::serialize<GameProtocol>(id, h);
}
// ...
};
只需编写另一个函数,将模板函数封装在您的GameProtocol类中:
static Packet* serialize(int packetId, QVariantHash data = QVariantHash()) {
return serialize<GameProtocol>( packetId, data );
}
现在你可以摆脱模板:
GameProtocol::serialize(0);
相关文章:
- 标准对此指向成员函数类型模板参数有何说明?是我的代码有误,还是 MSVS 16.6 有问题?
- 避免在人为的重载函数调用中拼写出类型
- 有没有办法避免为 std::variant 类成员中的所有类型编写构造函数?
- 避免使用 std::any 编写相同的重复类型检查代码
- 如何避免模板函数返回类型重复?
- 如何避免具有相同类型参数的函数中的错误
- 避免从单一元素向量转换为基元类型
- 避免对非类类型使用指向成员函数的指针
- 避免在禁用复制的 POD 类型的内存上使用"-Wclass-memaccess"
- 在完美转发函数中公开参数类型,避免代码重复
- 当类型为参数时如何避免类型化
- 如何构建程序以避免查询对象类型?
- 有了C++类型特征,有没有办法避免铸造
- 避免将 Int 转换为双重类型转换舍入
- 工会如何用于避免类型覆盖
- 根据数据包类型更改行为,避免开关语句
- 两种类型转换有何不同?
- 如何避免使用模板类型的派生类进行多态性动态强制转换
- 避免在字符串中分支 if-else 以类型调度
- 如何避免隐式转换类型