如何避免使用类型名称类型

How can I avoid using the type name type

本文关键字:类型 何避免      更新时间:2023-10-16

我的基类中有一个声明:

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);