c++ - 为什么从 C++11 中删除了 unary_function、binary_function?

标签 c++ c++11 stl functor unary-function

我发现 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。如何提供这些 typedef 应该取决于实现。

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

编辑

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

你不需要它。

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: a generalized negator

关于c++ - 为什么从 C++11 中删除了 unary_function、binary_function?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22386882/

相关文章:

c++步骤作为效率

c++ - 对 C++ 多态、可查找、二进制 I/O 接口(interface)的建议

c++ - "atomic"和 "cstdatomic"有什么区别?

c++ - 我在这里没有正确使用 typeof() 吗?

c++ - boost1.53协程的bug?

c++ - 当我所做的只是将循环代码移动到函数中时,代码运行速度慢了十倍

c++ - 在 Visual Studio 2013 for C++ 中调试时的错误代码

c++ - 使用 wregex 会产生垃圾输出?

c++ - 从派生类调用的复制构造函数

c++ - 如何重置 shared_ptr?