代码之家  ›  专栏  ›  技术社区  ›  KennyTM

如何将一个函数绑定到另一个函数

  •  1
  • KennyTM  · 技术社区  · 7 年前

    我有一个功能 A 接受谓词函数作为其参数的。
    我还有一个功能 B 它需要一个 char 返回一个 int 和一个函数 C 接受 int 返回一个 bool .

    我的问题是如何绑定 乙 和 C 传递给函数 一 .

    类似:

    A(bindfunc(B,C))
    

    我知道 boost::bind 有效,但我正在寻找STL解决方案。

    例如,

    int count(vector<int> a, pred func);    // A
    //this functions counts all elements which satisfy a condition
    int lastdigit(int x);                   // B
    //this function outputs last digit(in decimal notation) of number x
    bool isodd(int x);                      // C
    //this function tells if number x is odd
    
    // i want to find the count of all such numbers in a vector whose last digit is odd
    // so i want something like
    count(vector<int> a, bind(lastdigit, isodd))
    

    一个不好的方法是做一个冗余的函数 D 它显式执行绑定操作。

    2 回复  |  直到 16 年前
        1
  •  3
  •   Alexandre C.    16 年前

    作为一个简单的解决方法 compose 高阶函数 std :

    template <typename F1, typename F2>
    struct composer : 
        std::unary_function
        <
            typename F2::argument_type, 
            typename F1::result_type
        >
    {
        composer(F1 f1_, F2 f2_) : f1(f1_), f2(f2_) {}
    
        typename F1::result_type 
        operator()(typename F2::argument_type x)
        { return f1(f2(x)); }
    
    private:
        F1 f1;
        F2 f2;
    };
    
    template <typename F1, typename F2>
    composer<F1, F2> compose(F1 f1, F2 f2) 
    { return composer<F1, F2>(f1, f2); }
    

    注意,它不适用于二进制函数(涉及更多的工作),并且您的函数必须是STL函数对象。这意味着如果您有函数指针,则必须用 std::ptr_fun .

        2
  •  1
  •   Bill Lynch    16 年前

    我不相信STL的绑定函数对于您的需求是足够通用的。