gpt4 book ai didi

C++ std::mem_fn 和 std::bind 反过来

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:05:34 25 4
gpt4 key购买 nike

因此,我一直在研究使用抽象算法在我的代码中重用重复出现的模式。具体来说,我想确定节点数组中具有最高“分数”的元素,这是通过评估复杂的评分成员函数来确定的。

some help 之后我想出了 (C++17)

template <typename FwdIt, typename Eval, typename Pred = std::less<>>
constexpr FwdIt max_eval_element(FwdIt first, FwdIt last, Eval eval, Pred pred = Pred()) {
FwdIt found = first;
if (first != last) {
auto best = eval(*found);
while (++first != last) {
if (auto const thisVal = eval(*first);
pred(best, thisVal)) {
found = first;
best = thisVal;
}
}
}
return found;
}

考虑一下我的 Node 类:

class Node {
private:
double val;
public:
Node(double val) noexcept : val(val) {}

[[nodiscard]] auto Score1() const noexcept {
return std::sqrt(std::log(10.0 / val));
}

[[nodiscard]] auto Score2(double other) const noexcept {
return std::sqrt(std::log(other / val));
}
};

和我的节点数组:

std::array<Node, 100000> nodes;

我可以打电话

auto const& Node = *std::max_eval_element(std::cbegin(nodes), std::cend(nodes), std::mem_fn(&Node::Score1));

但现在我想为 Score2 重复此操作,其中输入取决于一些局部变量...当然我可以编写一些 lambda 函数...但我们有 std: :bind 对吧?我知道你可以像

这样的成员函数调用绑定(bind)
std::bind(this, std::mem_fn(Node::Score1));

但我想要的是相反的方式。哪个不起作用。

auto const& Node = *std::max_eval_element(std::cbegin(nodes), std::cend(nodes), std::bind(std::mem_fn(&Node::Score2), 1.0));

我也试过,还是不行

auto const& Node = *std::max_eval_element(std::cbegin(nodes), std::cend(nodes), std::mem_fn(std::bind(&Node::Score2), 1.0));

我知道为什么这不起作用...成员函数需要对象指针作为(隐藏的)第一个参数。但这将意味着我们缺少诸如 std::bind_mem_fn 之类的东西......我们过去有 std::bind2nd ,但它已在 C+ 中删除+17...

再说一次:我当然可以使用 lambda,但考虑到像 std:mem_fnstd::bind 这样的东西存在,抽象算法是一件好事。 .

我是不是遗漏了什么,或者这只是标准中遗漏的?

最佳答案

调用 std::bind(&Node::Score2) 是问题所在。它缺少传递给 Score2 的参数。你想要:

std::bind(&Node::Score2, std::placeholders::_1, 1.0)

这不是指向成员的指针,因此它不是 std::mem_fn 的适当参数

或者,您可以使用 lambda

[](const auto & node) { return node.Score2(1.0); }

关于C++ std::mem_fn 和 std::bind 反过来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58538950/

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