首页 > 解决方案 > 什么是 C++17 中 std::unary_function 的等效替代品?

问题描述

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

'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
    }
};

标签: c++stlc++17

解决方案


std::unary_function以及许多其他基类,例如std::not1orstd::binary_functionstd::iterator已逐渐弃用并从标准库中删除,因为不需要它们。

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

在您的示例中,您可以简单地从以下位置删除继承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
    }
};

推荐阅读