简体   繁体   中英

Directly call the return functor from bind1st and bind2nd

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?

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, eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM