绕过Qt的模板限制

Getting around Qt's templating restrictions

本文关键字:Qt 绕过      更新时间:2023-10-16

我想用C++编写一个简单的灵活的ftp服务器,可以用一个类进行参数化,以处理服务器初始化时提供的用户(检查登录名和密码,交付文件等)。

所以我想出了这个巧妙(所以我想)的想法:

class FtpDelegate
{
public:
    FtpDelegate() {}
    virtual ~FtpDelegate() {}
    virtual bool login(QString username, QString password) = 0;
    // ...
};
class DummyDelegate : public FtpDelegate
{
public:
    virtual bool login(QString username, QString password)
    {
        return true;
    }
};
template<class Delegate>
class FtpServer : public QObject, Derived_from<Delegate, FtpDelegate>
{
    Q_OBJECT
public:
    explicit FtpServer(const QHostAddress &address = QHostAddress::Any,
                       quint16 port = 21,
                       QObject *parent = 0);
public slots:
    void newConnection();
private:
    QTcpServer *server;
    QHostAddress address;
};
template <class Delegate>
void FtpServer<Delegate>::newConnection()
{
    FtpDelegate *delegate = new Delegate();
    new FtpConnection (delegate, server->nextPendingConnection(), address, this);
}
class FtpConnection : public QObject
{
    Q_OBJECT
public:
    explicit FtpConnection(FtpDelegate *delegate,
                           QTcpSocket *socket,
                           const QHostAddress &address,
                           QObject *parent = 0);
public slots:
    void newDataConnection();
private:
    QTcpSocket *socket;
    QTcpServer *dataServer; // needed to transfer data to user
    QTcpSocket *dataSocket;
};

// server initialization
FtpServer<DummyDelegate> ftpServer();

然后(你可能看到了)砰!

Error: Template classes not supported by Q_OBJECT

很可能还有其他错误或误解,因为我才刚刚开始学习C++模板机制(以及Qt)。

我的问题是:在不使用诸如传递函数指针或需要为每个具体的 FtpDelegate 的派生类创建工厂实现的情况下,让它工作的最佳方法是什么。也许有一些我看不到的聪明设计模式。最终,如果它是最佳选择,我可以重写网络机制以提升。

无法

Q_OBJECT类创建模板(请参阅此处和答案)。

不应使用静态继承,

而应使用运行时继承,并注入从 FtpDelegate 类继承的对象。


看起来 FtpServer 实际上是一个创建连接的工厂。从你的问题中,我不明白为什么它必须是Q_OBJECT类。因此,您可能需要重新考虑您的设计,并简化该类。


使用它工作的最佳方法是什么,而无需使用丑陋的技巧,例如传递函数指针或需要为每个具体的 FtpDelegate 的派生类创建工厂实现。

最好的方法可能是拥有一个工厂类,它创建FtpDelegate类型的实例。但是您在发布的代码中存在很多问题,以至于如果不了解所有血腥的细节,就不可能说出更多。