Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is an equivalent replacement for std::unary_function in C++17?

Tags:

c++

c++17

stl

Here is the code that's causing me some issues, trying to build and getting the error:

'unary_function base class undefined' and 'unary_function' is not a member of std'

std::unary_function has been removed in C++17 so what is an equivalent version?

#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
    }
};
like image 981
TMStackO Avatar asked Aug 25 '20 10:08

TMStackO


1 Answers

std::unary_function and many other base classes such as std::not1 or std::binary_function or std::iterator have been gradually deprecated and removed from the standard library, because there is no need for them.

In modern C++, concepts are being used instead. It is not relevant whether a class inherits specifically from std::unary_function, it just matters that it has a call operator which takes one argument. This is what makes it a unary function. You would detect this by using traits such as std::is_invocable in combination with SFINAE or requires in C++20.

In your example, you can simply remove the inheritance from 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
    }
};
like image 144
Jan Schultke Avatar answered Nov 02 '22 21:11

Jan Schultke