C++17 中 std::unary_function 的等效替代品是什么?

TMS*_*ckO 11 c++ stl c++17

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

“unary_function 基类未定义”和“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
    }
};
Run Code Online (Sandbox Code Playgroud)

Jan*_*tke 15

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

在现代 C++ 中,概念正在被使用。一个类是否专门从 继承std::unary_function无关紧要,重要的是它有一个带一个参数的调用运算符。这就是使它成为一元函数的原因。您可以通过使用特征来检测这一点,例如std::is_invocableSFINAErequiresC++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
    }
};
Run Code Online (Sandbox Code Playgroud)