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

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

本文关键字:function binary unary c++ 删除 为什么      更新时间:2023-10-16

我发现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;}
};
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;
};

----------------------------------------------------------------------------

template<class arg,class result>
struct unary_function
{
       typedef arg argument_type;
       typedef result result_type;
};

例如,如果我们想在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

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

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

在标准中不再使用,因为要求从binary_function派生实现是过度规范的。

用户不需要关心less是否从binary_function派生而来,只需要关心它定义了first_argument_typesecond_argument_typeresult_type。这应该取决于实现如何提供这些类型。

强制实现从特定类型派生意味着用户可能开始依赖于该派生,这没有意义,也没有用。

编辑

如果没有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);
           }
}

事实上你可以做得更好,参见not_fn:一个广义负子

使用可变模板,许多通用函数组合可以更简单和一致地表示,因此不再需要所有旧的繁琐操作:

做使用:

  • std::function
  • std::bind
  • std::mem_fn
  • std::result_of
  • λ

不要使用:

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