直接从bind1st和bind2nd中调用返回函子

Directly call the return functor from bind1st and bind2nd

本文关键字:调用 返回 bind2nd bind1st      更新时间:2023-10-16

bind1st和bind2nd的返回值源自一元函数。通过调用它们,我认为它们提供了一个接受一个参数的函数对象。但这可能是错误的。

这是我的密码。

template<typename _T>
class fun: public std::unary_function<_T, _T>
{
public:
    _T operator()(_T arg1, _T arg2) const {return arg1 + arg2;}
};
int main() {
    bind2nd(fun<int>(),10)(10); //My intention is to directly call the results of bind2nd
}

会出现很多构建错误。为什么这是错误的?

我相信一元函数对一个参数进行运算,而二元函数对两个参数进行操作。例如

  T operator()(T arg1, T arg2) const {return arg1 + arg2;}

是一个二进制函数。

更改模板(并考虑不使用领先的欠交叉):

template<typename T>
class fun: public std::binary_function<T, T, T>
//                     ^^^^^^--- well, it takes two parameters
{
public:
    T operator()(T arg1, T arg2) const {return arg1 + arg2;}
};

因此,fun是一个二元函子绑定了它的一个参数之后,例如通过调用std::bind2nd(func<int>(),10),您将获得一个一元函数。这不会改变bind2nd调用的输入类型。