我想将Qt的mappedReduced
与lambdas一起使用。
使用lambda 进行 QtConcurrent::map 工作的答案似乎表明这不可能直接实现,但可以通过使用std::function
来实现。
但是,虽然我可以构建编译器接受的调用来mapped()
这种方式,但我无法弄清楚如何以编译器想要编译的方式将原则应用于mappedReduced()
。这必须如何制定?
简单的例子:
int cap = 1;
std::function<int(char)> mlf = [cap](char c){ return static_cast<int>(c)+cap; };
std::function<void(double&,int const&)> rlf = [cap](double &d,int const &i){ d += static_cast<double>(i+cap); };
QVector<char> seq = {'a','b','c'};
QVector<int> v = QtConcurrent::blockingMapped( seq, mlf );
double d = QtConcurrent::blockingMappedReduced( seq, mlf, rlf );
[注意:最终代码必须支持捕获,因此我在此示例中包括捕获。删除捕获不会让编译器在这里感到高兴。
IDE/编译器抱怨:
qtsupplement.cpp:291:17: error: no matching function for call to 'blockingMappedReduced'
qtconcurrentmap.h:199:12: note: candidate template ignored: couldn't infer template argument 'ResultType'
qtconcurrentmap.h:213:65: note: candidate template ignored: substitution failure [with MapFunctor = std::function<int (char)>, ReduceFunctor = std::function<void (double &, const int &)>, Sequence = QVector<char>]: implicit instantiation of undefined template 'QtPrivate::ReduceResultType<std::function<void (double &, const int &)> >'
qtconcurrentmap.h:228:12: note: candidate function template not viable: requires at least 4 arguments, but 3 were provided
qtconcurrentmap.h:243:65: note: candidate function template not viable: requires at least 4 arguments, but 3 were provided
而"ResultType"应该是变量的类型d
并且rlf()
的第一个参数也提示结果类型。
使用版本: qt5.5.1, g++5.4.0, qtcreator4.9.0
以下代码对我有用(Qt 6.0.3,C++17(:
int cap = 1;
QVector<char> seq = {'a','b','c'};
QVector<int> v = QtConcurrent::blockingMapped<QVector<int>>(
seq,
[cap](char c){ return static_cast<int>(c)+cap; }
);
double d = QtConcurrent::blockingMappedReduced<double>(
seq,
[cap](char c){ return static_cast<int>(c)+cap; },
[cap](double &d,int const& i){ d += static_cast<double>(i+cap); }
);
因此,您应该使用 Qt 6.0.3 并指定模板参数。