Milad Sikaroudi
Milad Sikaroudi

Reputation: 717

How do I replace std::binary_function with something else without pain?

We are currently using some 3rd party packages which use some std::binary_function, std::unary_function deep inside. As you might know, these functions had been deprecated in C++14, and now they all have been removed from C++17. We are going to use some new features of C++17 and simultaneously we are not going to make some major changes since it might lead to some instability in our codes. How do we simply replace these legacy C++ features(std::binary_function,...) with something else with lesser pain.

Thank you in advance for your help.

Upvotes: 3

Views: 3363

Answers (1)

Dmitry Gordon
Dmitry Gordon

Reputation: 2324

I don't know any existing types in standard library, but it's not a big deal to create your own:

template<class Arg1, class Arg2, class Result> 
struct binary_function
{
    using first_argument_type = Arg1;
    using second_argument_type = Arg2;
    using result_type = Result;
};

template <typename ArgumentType, typename ResultType>
struct unary_function
{
    using argument_type = ArgumentType;
    using result_type = ResultType;
};

Both of these classes are just simple base classes for user-defined functional objects, e.g.:

struct MyFuncObj : std::unary_function<int, bool>
{
    bool operator()(int arg) { ... }
};

Having aliases for arguments allowed to use some standard library built in functionality, e.g. std::not1: std::not1(MyFuncObj()).

My guess why this was deprecated is because after C++11 mostly lambdas are used to create functional objects. And having variadic templates it's quite easy to create generic version of not and other things without having std::not1, std::not2.

Upvotes: 4

Related Questions