gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 21:37:06 51 4
gpt4 key购买 nike

我发现 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/

51 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com