Question

The return values of bind1st and bind2nd are derived from unary_function. By calling them, I think they provide a function object that accepts one argument. But this maybe is wrong.

Here is my code.

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
}

A lot of build errors occur. Why is this wrong?

Was it helpful?

Solution

I believe a unary function operates on one parameter, while a binary function operates on two. For example

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

is a binary_function.

Change the template (and consider not using leading underscroes):

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;}
};

So, fun is a binary functor. After you bind one of its arguments, e.g. by calling std::bind2nd(func<int>(),10) you will then have a unary function. This will not alter the type of the input to the bind2nd call.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top