因此,我一直在研究使用抽象算法在代码中重用重复发生的模式。具体来说,我想确定节点数组中具有最高“得分”的元素,这是通过对复杂的评分成员函数进行评估来确定的。]
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_fn
和std::bind
之类的东西,并且抽象算法是一件好事...
我是否缺少某些内容,或者这只是标准中缺少的内容?
因此,我一直在研究使用抽象算法在代码中重用重复发生的模式。具体来说,我想确定节点数组中具有最高“得分”的元素,...
呼叫std::bind(&Node::Score2)
是问题。它缺少传递给Score2
的参数。您想要:
std::bind(&Node::Score2, std::placeholders::_1, 1.0)
我得出的结论是,lambda的优化优于std :: mem_fn