Why have unary_function, binary_function been removed from C++11?

后端 未结 2 678
春和景丽
春和景丽 2020-12-09 04:29

I found that binary_function is removed from C++11. I am wondering why.

C++98:

template  struct less : binary_function &l         


        
相关标签:
2条回答
  • 2020-12-09 04:59

    It isn't removed, it's just deprecated in C++11. It's still part of the C++11 standard. You can still use it in your own code. It was removed in C++17 though.

    It isn't used in the standard any more because requiring implementations to derive from binary_function is over-specification.

    Users should not care whether less derives from binary_function, they only need to care that it defines first_argument_type, second_argument_type and result_type. It should be up to the implementation how it provides those typedefs.

    Forcing the implementation to derive from a specific type means that users might start relying on that derivation, which makes no sense and is not useful.

    Edit

    How can we improve this in c++11 without unary_function?

    You don't need it.

    template<typename adaptableFunction>
    class unary_negate
    {
       private:
           adaptableFunction fun_;
       public:
           unary_negate(const adaptableFunction& f):fun_(f){}
    
           template<typename T>
               auto operator()(const T& x)  -> decltype(!fun_(x))
               {
                   return !fun_(x);
               }
    }
    

    In fact you can do even better, see not_fn: a generalized negator

    0 讨论(0)
  • 2020-12-09 05:16

    With variadic templates, a lot of general function composing can be expressed much more simply and consistently, so all of the old cruft is no longer necessary:

    Do use:

    • std::function
    • std::bind
    • std::mem_fn
    • std::result_of
    • lambdas

    Don't use:

    • std::unary_function, std::binary_function
    • std::mem_fun
    • std::bind1st, std::bind2nd
    0 讨论(0)
提交回复
热议问题