Std :: function comparison for member functions

I tried to search here for similar questions:
question 1
question 2

But I cannot compare member functions anyway. Here's an example:

class ClassA
{
public:
    int add(int a, int b)
    {
        return a + b;
    }
};

int main()
{
    ClassA a1{};

    function<int(int, int)> f1 = bind(&ClassA::add, a1, placeholders::_1, placeholders::_2);
    function<int(int, int)> f2 = bind(&ClassA::add, a1, placeholders::_1, placeholders::_2);

    cout << boolalpha << "f1 == f2 " << (f1.target_type() == f2.target_type()) << endl; // true
    cout << (f1.target<int(ClassA::*)(int, int)>() == nullptr) << endl; // true

    return 0;
}

      

It is obvious from the code that f1 and f2 are different. The first cout shows true because the types are the same, that's fine. But why is the second cout true ? Why does :: target () function return nullptr ?

PS: I want to create a simple delegate system so that I can pass any function (global, static, member). With std :: function, I can add a callback, but I don't know how to remove it.

+3


source to share


2 answers


That f1

target type is not int(ClassA::*)(int, int)

. Its target type will be the result of this expression bind

, which happens in gcc:

std::_Bind<std::_Mem_fn<int (ClassA::*)(int, int)> (
    ClassA, 
    std::_Placeholder<1>, 
    std::_Placeholder<2>)>

      

What you can see with the ABI demanger:



#include <cxxabi.h>
// note, the following line technically leaks, but 
// for illustrative purposes only it fine
cout << abi::__cxa_demangle(f1.target_type().name(), 0, 0, 0) << endl;

      

Note that if the target type was actually a class method, you could not name it with two int

- you will need it as well ClassA*

. For example, this target function type int(ClassA::*)(int, int)

:

function<int(ClassA*, int, int)> f3 = &ClassA::add;

      

+4


source


Those std::function

do not contain member functions. They contain result types bind

. Since it bind

is the same type template, the types of the results are the bind

same.



+2


source







All Articles