我有这个错误
error: cannot convert ‘<lambda(double)>’ to ‘double (*)(double)’从代码中
void Matrice::mapEmplace(double (*fct)(double))
{
for (size_t i = 1; i <= nLig; ++i)
for (size_t j = 1; j <= nCol; ++j)
(*this)(i, j) = (*fct)((*this)(i, j));
}--
void function()
{
// ...
bool alea = something;
// alea results on reading in a file
utilisation.mapEmplace(
[alea](double x) -> double {
return alea ? 1 : 0;
}
);
//....
}例如,当我不通过声明全局来捕获alea时,它就能工作。但是,当我在函数范围内声明alea时,g++会显示这个错误。
您知道问题是什么吗?我如何通过将alea保持在我的函数的局部位置来解决它?
发布于 2020-06-12 22:38:59
您只能转换the capture-less lambda to a c-style function pointer。在您的示例中,lambda通过复制捕获alea,因此不可能将函数指针类型转换为函数指针类型。
你有两个选择:
std::function,使函数成为一个模板函数,这样编译器就可以推断lambda的类型。模板void::mapEmplace(This){ for (size_t i= 1;i <= nLig;++i) for (size_t j= 1;j <= nCol;++j) (*this)(i,j) =fct(*this)(i,j);}发布于 2020-06-12 22:25:45
std::function是专门为处理捕获λ而设计的。因此,将其替换为:
void Matrice::mapEmplace(double (*fct)(double)) {
for(size_t i = 1; i <= nLig; ++i)
for(size_t j = 1; j <= nCol; ++j)
(*this)(i,j) = (*fct)((*this)(i,j));
}在这方面:
void Matrice::mapEmplace(std::function<double(double)> fct) {
for(size_t i = 1; i <= nLig; ++i)
for(size_t j = 1; j <= nCol; ++j)
(*this)(i,j) = fct((*this)(i,j));
}并在cpp文件的顶部添加#include <functional>。
https://stackoverflow.com/questions/62353259
复制相似问题