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

时间:2013-12-12 15:25:12

标签: c++ functor bind2nd

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

这是我的代码。

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
}

发生了很多构建错误。为什么这是错的?

1 个答案:

答案 0 :(得分:3)

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

  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调用的输入类型。