c++ - 如何用其他东西替换 std::binary_function 而不会痛苦?

标签 c++ templates c++17 deprecated legacy-code

我们目前正在使用一些 3rd 方包,这些包在内部使用了一些 std::binary_function、std::unary_function。您可能知道,这些函数在 C++14 中已被弃用,现在它们都已从 C++17 中删除。我们将使用 C++17 的一些新功能,同时我们不会进行一些重大更改,因为这可能会导致我们的代码出现一些不稳定的情况。我们如何简单地用其他东西替换这些遗留的 C++ 功能(std::binary_function,...)而痛苦较小。

预先感谢您的帮助。

最佳答案

我不知道标准库中的任何现有类型,但是创建自己的类型没什么大不了的:

template<class Arg1, class Arg2, class Result> 
struct binary_function
{
    using first_argument_type = Arg1;
    using second_argument_type = Arg2;
    using result_type = Result;
};

template <typename ArgumentType, typename ResultType>
struct unary_function
{
    using argument_type = ArgumentType;
    using result_type = ResultType;
};

这两个类都只是用户定义的功能对象的简单基类,例如:

struct MyFuncObj : std::unary_function<int, bool>
{
    bool operator()(int arg) { ... }
};

为参数设置别名允许使用一些标准库内置功能,例如std::not1:std::not1(MyFuncObj())

我猜这被弃用的原因是因为在 C++11 之后,主要使用 lambda 来创建函数对象。有了可变参数模板,就可以很容易地创建 not 和其他东西的通用版本,而无需 std::not1std::not2

关于c++ - 如何用其他东西替换 std::binary_function 而不会痛苦?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56001160/

相关文章:

c++ - 通过检查条件并重新检查来获取锁

c++ - C++14 中的 Lambda-Over-Lambda

c++ - 了解 std::vector 规范

html - 是否有工具可以将任何网站转换成其框架正在使用的模板?

c++ - 编译普通/模板函数的差异,C++

c++ - 按位运算符,不是 vs xor 在分支中使用

c++ - 在可变参数模板函数中同时接受 int 和 class?

c++ - 自动解包一对迭代器

c++ - 你能 static_assert 一个元组只有一种类型满足特定条件吗?

c++ - 无法通过 std::ref() 使用 auto& 参数调用 std::invoke()