【问题标题】:C++ Type of a functor returned by bindbind 返回的函子的 C++ 类型
【发布时间】:2015-01-05 06:03:29
【问题描述】:

我目前正在用 C++ 编写一个国际象棋程序。搜索算法是 alphaBeta,这就是为什么我在遍历它们并评估它们之前对它们进行排序。我的主要类是 Position 类,它执行所有搜索,还包含一个比较两个 Move 的函数。

class Position{

    private:
    //This vector holds the moves of the current line, to be evaluated

    vector<Move> currentSearch(4000);

    // This function uses internal fields of class Position to determine, whether move1 or move2 should be searched first

    bool compare(const Move& move1, const Move& move2);

    int alphaBeta(int ply, int depth, int alpha, int beta);

}

现在要对 currentSearch 中的移动进行排序,我总是调用 alphaBeta

sort(currentSearch.begin(), currentSearch.end(), bind(mem_fn(&amp;Position::compare),this,_1,_2));

所以这会生成一个带有bind(mem_fn(&amp;Position::compare),this,_1,_2)); 的函子 在一次搜索中执行多次以生成相同的函子。

我希望有一个初始化为 bind(mem_fn(&amp;Position::compare),this,_1,_2)); 的 Position 类的成员,但是该成员必须具有什么类型,或者设计它的正确方法是什么?

【问题讨论】:

    标签: c++ functional-programming function


    【解决方案1】:

    根据我对 boost.bind(std bind 所基于)的经验,提前捕获结果没有多大意义。如上所述,该类型相当奇怪,仅在编译时存在。

    这是重点的一部分。 bind 背后的大部分工作都是在编译时完成的。类的初始化和使用 bind 时的函数调用一样简单。

    根据我的经验,绑定的魔力是在编译时使用模板完成的。

    【讨论】:

      【解决方案2】:

      我猜您使用的是 c++11,因为 std::bind 在以前的版本中不可用。

      来自http://en.cppreference.com/w/cpp/utility/functional/bind

      template< class F, class... Args >
      /*unspecified*/ bind( F&& f, Args&&... args );
      

      显然标准委员会不想将实现细节硬编码到标准中。

      因此,如果您真的需要将函子存储在某个地方,最好的选择是编写自己的函子类,而不是使用 lambda 或 std::bind。第二个最佳选择是使用std::function。它可以存储任何函数,例如具有兼容签名的东西,但存在运行时间接开销,您可能不希望在这里。

      或者您可以复制并粘贴相同的行,或者如果函子在同一个函数中重复使用,则使用 auto

      顺便说一句,当你使用std::bind时,不需要mem_fun

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-18
        • 1970-01-01
        相关资源
        最近更新 更多