我正在使用 Qt 5.3 和 MinGW 4.8.2(由于客户端限制,Qt 版本无法升级)。
尝试connect
带有 lambda 表达式的 QTcpSocket 最终会出现编译器错误。
我已经导入<QTcpSocket>
我的类(class)继承了 QObject
公开。 Q_OBJECT
宏也已添加到头文件中。
这就是我尝试将套接字连接到 lambda 函数的方式:
void TCPRequests::handleClient() {
QTcpSocket* sock = serv -> nextPendingConnection();
connect(sock, &QTcpSocket::readyRead, [sock]()
{
// Do nothing
});
}
这可以在 Qt 5.8 上正确编译和工作,但不能在使用 MinGW 4.8.2 的 5.3 上正确编译和工作。
我也尝试过
connect(sock, &QTcpSocket::readyRead, this, [sock]() {...});
(请注意,我还传递 this
作为第三个参数),但这没有什么区别。
产生的错误是:
第一:
D:\Documents\Development\X\TCPRequests.cpp:43: error: no matching function for call to 'TCPRequests::connect(QTcpSocket*&, void (QIODevice::*)(), TCPRequests::handleClient()::__lambda0)' });
第二:
D:\Documents\Development\X\TCPRequests.cpp:43: error: template argument for 'template static typename QtPrivate::QEnableIf<((int)(QtPrivate::FunctionPointer::ArgumentCount) >= 0), QMetaObject::Connection>::Type QObject::connect(const typename QtPrivate::FunctionPointer::Object*, Func1, Func2)' uses local type 'TCPRequests::handleClient()::__lambda0' });
第三:
D:\Documents\Development\X\TCPRequests.cpp:43: error: template argument for 'template static typename QtPrivate::QEnableIf<(QtPrivate::FunctionPointer::ArgumentCount == (-1)), QMetaObject::Connection>::Type QObject::connect(const typename QtPrivate::FunctionPointer::Object*, Func1, Func2)' uses local type 'TCPRequests::handleClient()::__lambda0' });
任何帮助将不胜感激!
最佳答案
您可能需要将 CONFIG += c++11
添加到项目文件(.pro
文件)中,以在项目中启用 c++11 功能。
之所以在 Qt 5.8 中不报错,是因为从 Qt 5.7.0 开始默认启用 c++11,并且不支持不支持 c++11 的旧编译器。请参阅note :
C++11 Support Required from the compiler
Qt has enabled usage of C++11 in Qt applications for a long time, but with Qt 5.7 we are also enabling use of C++11 in the Qt modules. Therefore Qt 5.7 requires C++11 support from the compiler, and has removed support from older compilers not providing adequate C++11 support.
关于c++ - Qt 5.3 连接 lambda,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42183070/