gpt4 book ai didi

c++ - 替换 std::binary_function

转载 作者:IT老高 更新时间:2023-10-28 21:56:23 25 4
gpt4 key购买 nike

std::binary_function现已弃用,将在 中删除.我搜索了不同的出版物,但我找不到替换它的确切方法。我想知道我应该如何在中编写以下代码风格。

template <class T>
inline T absolute(const T &x) {
return (x >= 0) ? x : -x;
}

template <class T>
struct absoluteLess : public std::binary_function<T, T, bool> {
bool operator()(const T &x, const T &y) const {
return absolute(x) < absolute(y);
}
};

template <class T>
struct absoluteGreater : public std::binary_function<T, T, bool> {
bool operator()(T &x, T &y) const {
return absolute(x) > absolute(y);
}
};

编辑

我正在通过以下方式使用这些功能:

output[j] = *std::max_element(input.begin() + prev,
input.begin() + pos,
absoluteLess<float>());

inputoutputstd::vector,在 for 循环中。

最佳答案

首先,我的建议是观看 CppCon 2015: Stephan T. Lavavej "functional: What's New, And Proper Usage" . std::binary_function 在幻灯片 36 中提到,视频大约 36 分钟。您可以在 github.com/CppCon/CppCon2015 找到幻灯片)。它没有详细说明为什么不应该使用 std::binary_function,但是如果您使用的是自 C++11 以来已被弃用的东西,那么您可能会从观看中受益。

如果您想了解不使用它的实际理由,请尝试 n4190:

unary_function/binary_function were useful helpers when C++98-era adaptors needed argument_type/etc. typedefs. Such typedefs are unnecessary given C++11's perfect forwarding, decltype, and so forth. (And they're inapplicable to overloaded/templated function call operators.) Even if a class wants to provide these typedefs for backwards compatibility, it can do so directly (at a minor cost in verbosity) instead of inheriting from unary_function/binary_function, which is what the Standard itself started doing when these helpers were deprecated.

现在您根本不需要它,因此您可以从程序中删除它的所有痕迹。

在 C++14 中,添加了透明比较器。但它可以在 C++11 中实现。只为 void 专门化它:

template<>
struct absoluteLess<void> {
template< class T, class U>
constexpr auto operator()( T&& lhs, U&& rhs ) const
-> decltype(absolute(std::forward<T>(lhs)) < absolute(std::forward<U>(rhs)))
{
return absolute(std::forward<T>(lhs)) < absolute(std::forward<U>(rhs));
}
}
};

现在可以推断出类型:

std::max_element(v.begin(), v.end(), absoluteLess<>());

关于c++ - 替换 std::binary_function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33114656/

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