Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

c++ - Make QtConcurrent::mapped work with lambdas

I am trying to use QtConcurrent::mapped into a QVector<QString>. I already tried a lot of methods, but it seems there are always problems with overloading.

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

This snippet returns the following error:

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

I saw this post, which says that Qt cannot find the return value of the lambda, so you have to use std::bind with it. If I try this:

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

But the the error is still similar:

/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);
                                                                                  ^

I also tried wrapping the lambda inside std::function but unfortunately similar results.

  • Note that this example is just for reproduction, I need a lambda because I am also capturing variables in my code.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The following compiles for me:

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

Output of qDebug() << result.results():

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...