使 QtConcurrent::mapped 与 lambda 一起工作

lha*_*ahn 3 c++ qt c++11

我正在尝试使用QtConcurrent::mappedQVector<QString>. 我已经尝试了很多方法,但似乎总是存在重载的问题。

\n\n
QVector<QString> words = {"one", "two", "three", "four"};\n\nusing StrDouble = std::pair<QString, double>;\n\nQFuture<StrDouble> result = QtConcurrent::mapped<StrDouble>(words, [](const QString& word) -> StrDouble {\n    return std::make_pair(word + word, 10);\n});\n
Run Code Online (Sandbox Code Playgroud)\n\n

该片段返回以下错误:

\n\n
/home/lhahn/dev/cpp/TestLambdaConcurrent/mainwindow.cpp:23: error: no matching function for call to \xe2\x80\x98mapped(QVector<QString>&, MainWindow::MainWindow(QWidget*)::<lambda(const QString&)>)\xe2\x80\x99\n });\n  ^\n
Run Code Online (Sandbox Code Playgroud)\n\n

我看到这篇文章,它说 Qt 找不到 lambda 的返回值,所以你必须使用std::bind它。如果我尝试这个:

\n\n
using StrDouble = std::pair<QString, double>;\nusing std::placeholders::_1;\n\nauto map_fn = [](const QString& word) -> StrDouble {\n    return std::make_pair(word + word, 10.0);\n};\n\nauto wrapper_map_fn = std::bind(map_fn, _1);\n\nQFuture<StrDouble> result = QtConcurrent::mapped<StrDouble>(words, wrapper_map_fn);\n
Run Code Online (Sandbox Code Playgroud)\n\n

但错误仍然相似:

\n\n
/home/lhahn/dev/cpp/TestLambdaConcurrent/mainwindow.cpp:28: error: no matching function for call to \xe2\x80\x98mapped(QVector<QString>&, std::_Bind<MainWindow::MainWindow(QWidget*)::<lambda(const QString&)>(std::_Placeholder<1>)>&)\xe2\x80\x99\n QFuture<StrDouble> result = QtConcurrent::mapped<StrDouble>(words, wrapper_map_fn);\n                                                                                  ^\n
Run Code Online (Sandbox Code Playgroud)\n\n

我也尝试将 lambda 包裹在里面std::function,但不幸的是类似的结果。

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

小智 5

以下内容为我编译:

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);
Run Code Online (Sandbox Code Playgroud)

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

(std::pair("oneone",10)、std::pair("twotwo",10)、std::pair("三三",10)、std::pair("fourfour",10))

  • 它之所以有效,是因为捕获列表中没有任何内容。QtConcurrent 不适用于带有捕获的 lambda 函数。 (2认同)
  • 正确:我的意思是 QtConcurrent::mapped 不适用于带有捕获的 lambda 函数 (2认同)