【问题标题】:STL: std::bind1st for std::unary_functionSTL:std::bind1st 用于 std::unary_function
【发布时间】:2015-05-18 19:19:39
【问题描述】:

AFAIK std::bind1st 接受一个二元仿函数和一个参数,并返回一个已绑定第一个参数的一元仿函数。 STL是否提供类似std::bind1st的函数,接受一元函数和一个参数,并返回一个不带参数的函数?

编辑:我需要一个比 C++11 更早的版本的解决方案(我没有放那个标签)

【问题讨论】:

  • 从 C++11 开始,std::bind 可以正常工作,lambda 也是如此。
  • boost::bind? Boost.Lambda/Boost.Phoenix?
  • @CaptainGiraffe C++03
  • @chris 我需要 STL 解决方案

标签: c++ stl functional-programming bind


【解决方案1】:

一种方法是自己编写活页夹

template<typename FUNCTION, typename ARG_TYPE, typename RETURN_TYPE>
struct bind_it
{
    FUNCTION function;
    ARG_TYPE argument;
    bind_it(ARG_TYPE value, FUNCTION f):function(f){
        argument = value;
    }

    RETURN_TYPE operator()(){
        return function(argument);
    }
};

我确信有更好的方法来编写活页夹。

并像使用它

int f(int i){
    return i + 2;
}

int main()
{
    bind_it<int(*)(int), int, int> bound(5, f);
    int se7en = bound();
}

【讨论】:

    【解决方案2】:

    看来,STL 没有提供解决方案(std::bind 来自 C++11),所以我的版本是:

    #include <iostream>
    #include <functional>
    
    template <typename Operation>
    class bound_unary_function
    : public std::unary_function<typename Operation::argument_type,
                                 typename Operation::result_type> {
        typedef bound_unary_function<Operation> _Self;
    
        Operation op;
        typename _Self::argument_type arg;
    
    public:
        bound_unary_function(const Operation& _op, const typename _Self::argument_type& _arg)
        : op(_op), arg(_arg) { }
    
        typename _Self::result_type operator()() {
            return op(arg);
        }
    };
    
    template <typename Operation>
    bound_unary_function<Operation> bind_unary_function(const Operation& op,
                                                        const typename Operation::argument_type& arg) {
        return bound_unary_function<Operation>(op, arg);
    }
    
    int inc(int x) {
        return ++x;
    }
    
    int main() {
        std::cout << "inc(0)=" << bind_unary_function(std::ptr_fun(inc), 0)() << '\n';
        return 0;
    }
    

    bind_unary_function 比显式构造 bound_unary_function 更方便,因为它具有自动模板参数推导功能。

    【讨论】:

      猜你喜欢
      • 2017-07-18
      • 2017-11-13
      • 1970-01-01
      • 2020-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-30
      • 1970-01-01
      相关资源
      最近更新 更多