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