为什么从C++ 11中删除了unary_function,binary_function?

cam*_*ino 13 c++ stl functor unary-function c++11

我发现它binary_function已从C++ 11中删除.我想知道为什么.

C++ 98:

template <class T> struct less : binary_function <T,T,bool> {
  bool operator() (const T& x, const T& y) const {return x<y;}
};
Run Code Online (Sandbox Code Playgroud)

C++ 11:

template <class T> struct less {
  bool operator() (const T& x, const T& y) const {return x<y;}
  typedef T first_argument_type;
  typedef T second_argument_type;
  typedef bool result_type;
};
Run Code Online (Sandbox Code Playgroud)

MODIFIED ------------------------------------------------- ---------------------------

template<class arg,class result>
struct unary_function
{
       typedef arg argument_type;
       typedef result result_type;
};
Run Code Online (Sandbox Code Playgroud)

例如,如果我们想在C++ 98中为函数编写适配器,

template <class T> struct even : unary_function <T,bool> {
  bool operator() (const T& x) const {return 0==x%2;}
};

find_if(bgn,end,even<int>()); //find even number

//adapter
template<typename adaptableFunction >
class unary_negate
{
   private:
       adaptableFunction fun_;
   public:
       typedef adaptableFunction::argument_type argument_type;

       typedef adaptableFunction::result_type result_type;  
       unary_negate(const adaptableFunction &f):fun_(f){}

       bool operator()(const argument_type&x) 
       {
           return !fun(x);
       }
}

find_if(bgn,end, unary_negate< even<int> >(even<int>()) ); //find odd number
Run Code Online (Sandbox Code Playgroud)

如何在没有C++ 11的情况下改进这一点unary_function

Ker*_* SB 18

使用可变参数模板,可以更加简单和一致地表达许多通用功能组合,因此不再需要所有旧的功能:

使用:

  • std::function
  • std::bind
  • std::mem_fn
  • std::result_of
  • lambda表达式

不要使用:

  • std::unary_function, std::binary_function
  • std::mem_fun
  • std::bind1st, std::bind2nd


Jon*_*ely 17

它没有被删除,它在C++ 11中被弃用了.它仍然是C++ 11标准的一部分.您仍然可以在自己的代码中使用它.它在C++ 17中删除了.

它不再在标准中使用,因为需要实现来源binary_function是过度规范.

用户不应该关心是否less来自binary_function,他们只需要关心它定义first_argument_type,second_argument_typeresult_type.它应该取决于它如何提供这些typedef的实现.

强制实现从特定类型派生意味着用户可能开始依赖于该派生,这没有任何意义并且没有用处.

编辑

如果没有unary_function,我们如何才能在c ++ 11中改进这一点?

你不需要它.

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);
           }
}
Run Code Online (Sandbox Code Playgroud)

事实上,你可以做得更好,见not_fn:一个广义的否定者