c++ - Qt 5.3 连接 lambda

标签 c++ qt c++11 events lambda

我正在使用 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/

相关文章:

c++ - 为什么 STL 为 std::container::begin 和 std::container::end 函数提供 const 重载?

c++ - 更新到 Xcode9 后,我得到 C++ 需要所有声明的类型说明符

c++ - 所有的临时分配都有唯一的地址吗?

python - 类似Win32风格的pyqt Window

c++ - 获得通用引用的优势,无需通用引用

c++ - 访问 char* 或 std::string 的元素是否更快?

c++模板和头文件

c++ - 如何从另一个类的函数调用std::async时传递另一个类的函数?

c++ - QT 5 给设计器添加继承自QGraphicsView的自定义widget

c++ - 如何使用 QSettings 在 Qt 应用程序中加载设置