C++17中std::unary_function的等效替代是什么? [英] What is an equivalent replacement for std::unary_function in C++17?

查看:37
本文介绍了C++17中std::unary_function的等效替代是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码给我带来了一些问题,尝试构建并得到错误:

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

推荐答案

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

在现代C++中,正在使用概念。类是否专门从std::unary_function继承并不重要,重要的是它有一个接受一个参数的调用操作符。这就是它是一元函数的原因。您可以通过将std::is_invocable等特征与C++20中的SFINAErequires结合使用来检测到这一点。

在您的示例中,您只需从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
    }
};

这篇关于C++17中std::unary_function的等效替代是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆