gpt4 book ai didi

c++ - 使用 C++20 多态性 Lambda 函数时出错

转载 作者:行者123 更新时间:2023-12-04 03:30:40 25 4
gpt4 key购买 nike

我正在尝试通过 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&)>)’

这里的代码有什么问题?

最佳答案

此示例中的主要问题是 lambda 不是 std::function .参见 this question .

CmpGenerator将其参数推导为 std::function<T(Process const&)> ,但 lambda 永远不会匹配它,因此推导失败。

此外,CmpGenerator 的正文尝试返回两个不同的 lambda 之一——它们具有不同的类型。这些 lambda 不能相互转换,因此条件表达式将失败。但是我们也无法推断出 CmpGenerator 的返回类型因为这两个不同的 lambda 有不同的类型。


我们可以从完全手动开始。 std::ranges::sort进行投影,这在这方面非常有帮助:

if (col == "PID") {
if (increasing) { // <== 'flag' is not a great name
std::ranges::sort(lst, std::less(), &Process::GetPid);
} else {
std::ranges::sort(lst, std::greater(), &Process::GetPid);
}
} else if (col == "CPU") {
// ...
}

这给出了我们需要抽象的结构:我们不是生成比较对象,而是生成对 sort 的调用.

即:

auto sort_by = [&](auto projection){ // <== NB: auto, not std::function
if (increasing) {
std::ranges::sort(lst, std::less(), projection);
} else {
std::ranges::sort(lst, std::greater(), projection);
}
};

if (col == "PID") {
sort_by(&Process::GetPid);
} else if (col == "CPU") {
sort_by(&Process::GetRatioCPU);
} else if (col == "COMMAND") {
sort_by(&Process::GetCmd);
}

关于c++ - 使用 C++20 多态性 Lambda 函数时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66901310/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com