我发现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
我们怎样才能改善这种在C ++ 11没有unary_function
?
它不会被删除,它只是不赞成使用C ++ 11。它仍然是C ++ 11标准的一部分。你仍然可以使用它在自己的代码。这下去除C ++ 17虽然。
它未在标准中使用了,因为需要实现从binary_function
导出过度规范。
用户不应该关心less
无论从binary_function
派生,他们只需要关心它定义first_argument_type
,second_argument_type
和result_type
。它应该是到它如何提供这些类型定义的实现。
强制执行由特定类型推导意味着用户可能会开始依赖上推导,这是没有意义的,是没有用的。
编辑
我们怎样才能改善这种在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
随着可变参数模板,很多一般的排版功能可以简单地表示和一致得多,因此,所有的老克鲁夫特的不再是必要的:
不要使用:
std::function
std::bind
std::mem_fn
std::result_of
不要使用:
std::unary_function
,std::binary_function
std::mem_fun
std::bind1st
,std::bind2nd