gpt4 book ai didi

c++ - 绕过 Qt 的模板限制

转载 作者:行者123 更新时间:2023-11-30 04:12:34 25 4
gpt4 key购买 nike

我想用 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 的派生类创建工厂实现这样丑陋的 hack 的情况下,让它工作的最佳方法是什么。也许有一些我看不到的巧妙设计模式。最终我可以重写网络机制以提升它是否是最佳选择。

最佳答案

不可能创建模板 Q_OBJECT 类(参见 this 和答案)。

您应该使用运行时继承,而不是使用静态继承,并注入(inject)一个从 FtpDelegate 类继承的对象。


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


what is the best way to make it work without using ugly hacks like passing function pointers or needing to create a factory implementation for each concrete FtpDelegate's derived class.

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

关于c++ - 绕过 Qt 的模板限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19793447/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com