【发布时间】:2021-06-28 06:18:09
【问题描述】:
我正在尝试通过 C++ 中的 Lambda 编写一个高阶函数,并得到了这段代码。
void ProcessList::SortCol(std::string col, bool flag) {
auto CmpGenerator = [&]<typename T>
(std::function<T(const Process &itm)> func) {
return (flag? [&](const Process &a, const Process &b) {
return func(a) < func(b);}
: [&](const Process &a, const Process &b) {
return func(a) > func(b);}
);
};
std::function<bool(const Process &a, const Process &b)> cmp;
if (col == "PID") {
cmp = CmpGenerator([](const Process &itm) {
return itm.GetPid();
});
}
else if (col == "CPU") {
cmp = CmpGenerator([](const Process &itm) {
return itm.GetRatioCPU();
});
}
else if (col == "COMMAND") {
cmp = CmpGenerator([](const Process &itm) {
return itm.GetCmd();
});
}
std::sort(lst.begin(), lst.end(), cmp);
}
但是在编译时,g++ 报告调用不匹配
no match for call to ‘(ProcessList::SortCol(std::string, bool)::<lambda(std::function<T(const Process&)>)>) (ProcessList::SortCol(std::string, bool)::<lambda(const Process&)>)’
这里的代码有什么问题?
【问题讨论】:
-
您不能为此使用
std::ranges::sort(),并投影到指向成员(-函数)的指针吗? -
相当正确,但我想知道为什么这里的代码在地球上不起作用
-
除此之外:即使它可以正确推断出 T,
CmpGenerator也会返回一个捕获到func的悬空引用的 lambda
标签: c++ lambda c++20 higher-order-functions