【问题标题】:What is an equivalent replacement for std::unary_function in C++17?什么是 C++17 中 std::unary_function 的等效替代品?
【发布时间】:2020-12-14 01:00:33
【问题描述】:

这是导致我出现一些问题的代码,尝试构建并得到错误:

'unary_function base class undefined'和'unary_function'不是std的成员'

std::unary_function 已在 C++17 中删除,那么等效版本是什么?

#include <functional>

struct path_sep_comp: public std::unary_function<tchar, bool>
{ 
    path_sep_comp () {}

    bool
    operator () (tchar ch) const
    {
#if defined (_WIN32)
        return ch == LOG4CPLUS_TEXT ('\\') || ch == LOG4CPLUS_TEXT ('/');
#else
        return ch == LOG4CPLUS_TEXT ('/');
#endif
    }
};

【问题讨论】:

  • std::unary_function 已在 C++17 中删除。您可以删除它 - 不再需要了。
  • 标准库为所有以可调用对象作为参数的函数使用模板。你可以做同样的事情,而不是为path_sep_comp做任何继承。
  • IIRC,unary_function 在 C++17 之前的标准库中也不是严格需要的。您可以在仿函数中手动定义它为您提供的两个别名。现在不需要这些别名,因此,unary_function 也不需要。

标签: c++ stl c++17


【解决方案1】:

std::unary_function 和许多其他基类(例如 std::not1 或 std::binary_function 或 std::iterator)已逐渐被弃用并从标准库中删除,因为它们不再需要。

在现代 C++ 中,正在使用 概念。一个类是否专门从std::unary_function 继承无关紧要,重要的是它有一个带有一个参数的调用运算符。这就是使它成为一元函数的原因。您可以通过在 C++20 中结合使用 std::is_invocable 和 SFINAE 或 requires 等特征来检测这一点。

在您的示例中,您可以简单地从std::unary_function 中删除继承:

struct path_sep_comp
{
    // also note the removed default constructor, we don't need that
    
    // we can make this constexpr in C++17
    constexpr bool operator () (tchar ch) const
    {
#if defined (_WIN32)
        return ch == LOG4CPLUS_TEXT ('\\') || ch == LOG4CPLUS_TEXT ('/');
#else
        return ch == LOG4CPLUS_TEXT ('/');
#endif
    }
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-10
    • 1970-01-01
    • 2017-12-11
    相关资源
    最近更新 更多