我試圖使用QtConcurrent::mapped
到QVector<QString>
。我已經嘗試了很多方法,但似乎總會有超載的問題。使QtConcurrent :: mapped工作與lambdas
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找不到拉姆達的返回值,所以你必須使用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);
^
我也嘗試過包裝內std::function
但遺憾的是類似的結果拉姆達。
- 請注意,這個例子只是爲了複製,我需要一個lambda,因爲我也在我的代碼中捕獲變量。
顯然,QtConcurrent不支持lambda表達式尚未......作爲就像我可以從源代碼讀取的那樣,他們需要函數指針或成員函數指針:https://github.com/qt/qtbase/blob/dev/src/concurrent/qtconcurrentfunctionwrappers.h – Felix