C++ std::bindfirst


binder1st 是 C++ 标准库早期(在 C++11 之前)用于辅助函数对象绑定第一个参数的工具,它定义在 <functional> 头文件中。不过在 C++11 及以后, std::bindstd::bind_front 等更强大灵活的工具逐渐替代了它,但了解 binder1st 的源码实现有助于深入理解函数对象绑定的基本原理。

1. 基本功能和用途

binder1st 的主要功能是将一个二元函数对象(即接受两个参数的函数对象)的第一个参数固定为一个特定的值,从而生成一个新的一元函数对象。这样在后续调用这个新的一元函数对象时,就只需要提供原来二元函数对象的第二个参数即可。

2. 源码结构和实现细节

以下是简化后的 binder1st 源码示意(实际标准库实现可能会有更多的类型检查和兼容性处理等细节):

#include <functional>

// 模板类 binder1st 定义
template <class Operation>
class binder1st : public std::unary_function<typename Operation::first_argument_type,
                                             typename Operation::result_type> {
protected:
    Operation op;  // 存储原始的二元函数对象
    typename Operation::first_argument_type value;  // 存储要绑定的第一个参数的值

public:
    // 构造函数,接受二元函数对象和要绑定的第一个参数的值
    binder1st(const Operation& x,
              const typename Operation::first_argument_type& y) : op(x), value(y) {}

    // 重载函数调用运算符,实现一元函数对象的调用逻辑
    typename Operation::result_type
    operator()(const typename Operation::second_argument_type& x) const {
        return op(value, x);  // 调用原始二元函数对象,使用绑定的第一个参数和传入的第二个参数
    }
};

// 辅助函数,用于方便创建 binder1st 对象
template <class Operation, class T>
inline binder1st<Operation> bind1st(const Operation& op, const T& x) {
    return binder1st<Operation>(op, x);
}

3. 源码详细解析

模板类 binder1st
  • 模板参数Operation 是一个模板参数,表示要绑定的二元函数对象的类型。这个二元函数对象通常需要定义 first_argument_type(表示第一个参数的类型)、second_argument_type(表示第二个参数的类型)和 result_type(表示函数调用的返回值类型)。

  • 继承关系:继承自 std::unary_function<typename Operation::first_argument_type, typename Operation::result_type>,这是一个用于标记一元函数对象的基类,在 C++11 之前用于提供类型信息,方便其他标准库组件(如算法)使用。不过在 C++11 及以后,这种方式逐渐被废弃,更多使用类型推导等现代特性。

  • 成员变量

    • op:存储原始的二元函数对象,后续调用新的一元函数对象时会使用这个二元函数对象进行实际的操作。
    • value:存储要绑定的第一个参数的值,这个值在 binder1st 对象创建时就被固定下来。
  • 构造函数:接受一个二元函数对象 x 和一个要绑定的第一个参数的值 y,并将它们分别赋值给 opvalue 成员变量。

  • 重载 operator():这是实现一元函数对象调用逻辑的关键部分。它接受一个参数 x,这个参数是原来二元函数对象的第二个参数。在函数体中,调用原始的二元函数对象 op,并将预先绑定的第一个参数 value 和传入的第二个参数 x 传递给它,返回调用结果。

辅助函数 bind1st
  • 这是一个模板函数,接受一个二元函数对象 op 和一个要绑定的第一个参数的值 x
  • 它的作用是方便用户创建 binder1st 对象,避免用户手动指定模板参数,直接根据传入的参数类型自动推导 binder1st 的模板参数类型,然后创建并返回一个 binder1st 对象。

4. 使用示例

#include <iostream>
#include <functional>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 5};
    // 创建一个 greater 二元函数对象
    std::greater<int> greater_op;
    // 使用 bind1st 绑定 greater 的第一个参数为 3
    auto bound_op = bind1st(greater_op, 3);

    // 使用绑定后的一元函数对象进行计数
    int count = std::count_if(numbers.begin(), numbers.end(), bound_op);
    std::cout << "Numbers less than 3: " << count << std::endl;

    return 0;
}

在这个示例中,std::greater<int> 是一个二元函数对象,用于比较两个整数的大小。通过 bind1st 函数将其第一个参数绑定为 3,生成一个新的一元函数对象 bound_op。这个一元函数对象用于判断传入的参数是否小于 3。然后使用 std::count_if 算法统计 numbers 向量中小于 3 的元素个数。

5. 与现代 C++ 的对比

虽然 binder1st 在早期的 C++ 开发中发挥了重要作用,但它存在一些局限性,例如要求二元函数对象必须定义 first_argument_typesecond_argument_typeresult_type 等类型信息,不够灵活。在 C++11 及以后,std::bindstd::bind_front 等工具提供了更强大和灵活的参数绑定功能,不再依赖于这些固定的类型定义,并且可以处理更复杂的参数绑定和占位符使用等情况。不过理解 binder1st 的源码实现对于深入掌握函数对象绑定的基本原理仍然是有帮助的。

6. 手动实现mybind1st

#include <iostream>
#include <functional>
#include <vector>
#include <algorithm>
using namespace std;

template<typename T>
void ShowContainter(T con)
{
    typename T::iterator itr = con.begin();
    for (; itr != con.end(); ++itr)
    {
        cout << *itr << " ";
    }
    cout << endl;
}

template<typename com  , typename T>
class _mybindfirst
{
public:
    _mybindfirst(com _com , T _val) :_com(_com), val(_val) {}
    bool operator()(const T& second)
    {
        return _com(val , second);
    }
private:
    com _com;//函数
    T val;//容器
};

template<typename com , typename T>
_mybindfirst<com , T > mybindfirst(com _com ,const T&_val)
{
    return _mybindfirst<com, T >(_com, _val);
}

template<typename Iterator , typename Com>
Iterator myfindif(Iterator first, Iterator last, Com _com)
{
    for (; first != last; ++first)
    {
        if (_com(*first))
        {
            return first;
        }
    }
    return last;
}

int main() 
{
    srand(time(nullptr));//种一个随机种子
    vector<int> vec;
    for (int i = 0; i < 10; ++i)
    {
        vec.push_back(rand() % 100 + 1);
    }
    ShowContainter(vec);
    sort(vec.begin() , vec.end());
    ShowContainter(vec);
    sort(vec.begin(), vec.end() , less<int>());
    ShowContainter(vec);
    //以上是基础,下面开始调用bindfirst , 将50按照从小到大插入到vec
    auto ret = find_if(vec.begin(), vec.end(), bind1st(less<int>(), 50));
    if (ret == vec.end())
    {
        cout << "can not find it" << endl;
    }
    else
    {
        cout << "find it" << endl;
        vec.insert(ret, 50);
        ShowContainter(vec);
    }
    //以下代码开始根据bindfirst的原理 , 自己实现mybindfirst , 将60插入到vec
    auto ret1 = myfindif(vec.begin(), vec.end(),  mybindfirst(less<int>(), 60));
    if (ret1 == vec.end())
    {
        cout << "can not find it" << endl;
    }
    else
    {
        cout << "find it" << endl;
        vec.insert(ret1, 60);
        ShowContainter(vec);
    }
    return 0;
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值