2017-05-01 74 views
2

我試圖使用QtConcurrent::mappedQVector<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,因爲我也在我的代碼中捕獲變量。
+0

顯然,QtConcurrent不支持lambda表達式尚未......作爲就像我可以從源代碼讀取的那樣,他們需要函數指針或成員函數指針:https://github.com/qt/qtbase/blob/dev/src/concurrent/qtconcurrentfunctionwrappers.h – Felix

回答

2

下編譯對我來說:

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))

+0

它的工作原理是它在捕獲列表中沒有任何內容。 QtConcurrent不支持帶捕獲的lambda函數。 – benlau

+1

正確:我的意思是QtConcurrent :: mapped不能和lambda函數一起使用捕獲 – benlau

0

不幸的QtConcurrent ::映射不支持lambda函數與捕獲。你可能需要一個自定義的實現。例如,您可以製作一個與AsyncFuture:

template <typename T, typename Sequence, typename Functor> 
QFuture<T> mapped(Sequence input, Functor func){ 
    auto defer = AsyncFuture::deferred<T>(); 

    QList<QFuture<T>> futures; 
    auto combinator = AsyncFuture::combine(); 

    for (int i = 0 ; i < input.size() ; i++) { 
     auto future = QtConcurrent::run(func, input[i]); 
     combinator << future; 
     futures << future; 
    } 

    AsyncFuture::observe(combinator.future()).subscribe([=]() { 
     QList<T> res; 
     for (int i = 0 ; i < futures.size(); i++) { 
      res << futures[i].result(); 
     } 
     auto d = defer; 
     d.complete(res); 
    }); 

    return defer.future(); 
} 

用法:

auto future = mapped<int>(input, func); 

完整的例子:

https://github.com/benlau/asyncfuture/blob/master/tests/asyncfutureunittests/example.cpp#L326