Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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;
};

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

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

For example, if we want to write our adapter for function even in 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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
264 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...