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

问题描述 投票:0回答:2

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

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吧?我知道你可以在像>>这样的成员函数上进行绑定

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之类的东西,并且抽象算法是一件好事...

我是否缺少某些内容,或者这只是标准中缺少的内容?

因此,我一直在研究使用抽象算法在代码中重用重复发生的模式。具体来说,我想确定节点数组中具有最高“得分”的元素,...

c++ algorithm member-function-pointers
2个回答
2
投票

呼叫std::bind(&Node::Score2)是问题。它缺少传递给Score2的参数。您想要:

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

-1
投票

我得出的结论是,lambda的优化优于std :: mem_fn

© www.soinside.com 2019 - 2024. All rights reserved.