c++ - 使 QtConcurrent::mapped 与 lambda 一起工作

标签 c++ qt c++11

我正在尝试使用QtConcurrent::mapped进入QVector<QString> 。我已经尝试了很多方法,但似乎总是出现重载的问题。

QVector<QString> words = {"one", "two", "three", "four"};

using StrDouble = std::pair<QString, double>;

QFuture<StrDouble> result = QtConcurrent::mapped<StrDouble>(words, [](const QString& word) -> StrDouble {
    return std::make_pair(word + word, 10);
});

此代码片段返回以下错误:

/home/lhahn/dev/cpp/TestLambdaConcurrent/mainwindow.cpp:23: error: no matching function for call to ‘mapped(QVector<QString>&, MainWindow::MainWindow(QWidget*)::<lambda(const QString&)>)’
 });
  ^

我看到了这个post ,这表示 Qt 无法找到 lambda 的返回值,因此您必须使用 std::bind用它。如果我尝试这个:

using StrDouble = std::pair<QString, double>;
using std::placeholders::_1;

auto map_fn = [](const QString& word) -> StrDouble {
    return std::make_pair(word + word, 10.0);
};

auto wrapper_map_fn = std::bind(map_fn, _1);

QFuture<StrDouble> result = QtConcurrent::mapped<StrDouble>(words, wrapper_map_fn);

但是错误仍然相似:

/home/lhahn/dev/cpp/TestLambdaConcurrent/mainwindow.cpp:28: error: no matching function for call to ‘mapped(QVector<QString>&, std::_Bind<MainWindow::MainWindow(QWidget*)::<lambda(const QString&)>(std::_Placeholder<1>)>&)’
 QFuture<StrDouble> result = QtConcurrent::mapped<StrDouble>(words, wrapper_map_fn);
                                                                                  ^

我还尝试将 lambda 包裹在 std::function 内但不幸的是类似的结果。

  • 请注意,此示例仅用于重现,我需要一个 lambda,因为我还在代码中捕获变量。

最佳答案

以下内容为我编译:

QVector<QString> words = {"one", "two", "three", "four"};
std::function<StrDouble(const QString& word)> func = [](const QString &word) {
    return std::make_pair(word + word, 10.0);
};

QFuture<StrDouble> result = QtConcurrent::mapped(words, func);

qDebug() << result.results()的输出:

(std::pair("oneone",10), std::pair("twotwo",10), std::pair("threethree",10), std::pair("fourfour",10))

关于c++ - 使 QtConcurrent::mapped 与 lambda 一起工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43720869/

相关文章:

c++ - 移动指针的右值引用

C++ - 康威的生命游戏和后退

c++ - 即使没有焦点也想接收事件

c++ - 带赋值运算符的右值引用

c++ - 使用 C++ 和 Cimg 库将 RGB 图像转换为矩阵

c++ - Qt C++ : Line edit accept only alphanumeric characters, 破折号和下划线

C++11 在同一线程中执行 block 但超时

c++ - C++ 编译器是否优化按值返回成员变量

java - Android JNI - 从 C++ 调用 Android UI 线程上的函数

c++ - 需要 C++ HTML 解析器 + 正则表达式支持