2014-03-13 29 views
8

我發現從C++ 11中刪除了binary_function。我想知道爲什麼。爲什麼從C++ 11中刪除unary_function,binary_function?

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?

回答

10

它不會被刪除,它只是在C++ 11中被棄用。它仍然是C++ 11標準的一部分。你仍然可以在你自己的代碼中使用它。 (編輯:最近投票雖然從C++ 17刪除它的委員會。)

它不是在標準任何更多的使用,因爲需要實現從binary_function導出過度規範。

用戶不應該關心less無論從binary_function派生,他們只需要關心它定義first_argument_typesecond_argument_typeresult_type。它應該由實現如何提供這些typedef。

強制執行從特定類型派生意味着用戶可能會開始依賴於該派生,這是沒有意義的,也沒有用。

編輯

怎樣才能改善這種在C++ 11沒有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

12

隨着可變參數模板,很多一般功能組成的,可以簡單地和一貫表示要多得多,所以所有的老克魯夫特的不再是必要的:

確實使用:

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

不要使用:

  • std::unary_functionstd::binary_function
  • std::mem_fun
  • std::bind1ststd::bind2nd
+0

binary_function 可以簡化我們的工作,使代碼更一致的,對不對? – camino

+1

@camino:可以嗎? –

+0

沒有它,我們需要定義typedef T first_argument_type; ....,也許我們會忘記一些東西 – camino

相關問題