Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.0k views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...