绕过Qt的模板限制
Getting around Qt's templating restrictions
我想用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
类型的实例。但是您在发布的代码中存在很多问题,以至于如果不了解所有血腥的细节,就不可能说出更多。
相关文章:
- Qt VTK交互风格的信号到小部件
- QT在错误的班级中寻找空位
- 如何在选项卡视图Qt中设置一个新项目,并保存以前的项目
- 如何在Qt窗口小部件中使用QStringView(或QStringRef)
- 如何在Qt C++中更改光标
- 如何在MS Visual Studio 2019中运行QT UI
- QT通过C++添加映射QML项目
- libssh 的函数在构建 libssh 时无法在 Qt 和 cmake 错误中找到
- 如何将点击的信号和插槽添加到qt中的自定义按钮中
- Qt C++静态thread_local QNetworkAccessManager是线程应用程序的好选择吗
- 使用Qt C++计算类似Git的SHA1哈希
- Qt focusObjectChanged example?
- 如何在cpp文件之间切换窗口?在Qt中
- Qt和C++:将QLineEdit添加到QTabWidget中
- 从数据库实时显示QT c++中的数据
- Qt Quick-如何仅从c++代码与qml属性交互
- 无法使用Qt Creator在Windows中构建yaml-cpp
- 如何在Qt中取消捕获字符串
- Qt SQLite没有查询或参数计数不匹配
- 绕过Qt的模板限制