lundi 28 décembre 2020

Question about std::function when using with static member function

Why both PassFxn(&X::StaticMemberDoIt); and PassFxn(std::bind(&X::StaticMemberDoIt, _1, _2, _3)); are right? Is there is an implicit conversion when invoking PassFxn(&X::StaticMemberDoIt); since the declaration is void PassFxn(std::function<int(float, std::string, std::string)> func) other than void PassFxn(int(*func)(float, std::string, std::string))?

What the differences between PassFxn(&X::StaticMemberDoIt); and PassFxn(X::StaticMemberDoIt);?

Here is the code snippet(https://coliru.stacked-crooked.com/a/f8a0e1bb60550958) for demo:

#include <functional>
#include <string>
#include <iostream>

void PassFxn(std::function<int(float, std::string, std::string)> func)
//           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
{
   int result = func(12, "a", "b"); // call using function object
   std::cout << result << std::endl;
}

struct X
{
    int MemberDoIt(float f, std::string s1, std::string s2)
    {
        std::cout << "Member: " << f << ", " << s1 << ", " << s2 << std::endl;
        return 0;
    }

    static int StaticMemberDoIt(float f, std::string s1, std::string s2)
    {
        std::cout << "Static: " << f << ", " << s1 << ", " << s2 << std::endl;
        return 0;
    }
};

int main()
{
    using namespace std::placeholders;

    X x;
    PassFxn(std::bind(&X::MemberDoIt, x, _1, _2, _3)); // Use a member function!

    // Or, if you have a *static* member function...
    //Why these four expression are all right?
    PassFxn(X::StaticMemberDoIt);
    
    PassFxn(&X::StaticMemberDoIt);
    
    PassFxn(std::bind(X::StaticMemberDoIt, _1, _2, _3));
    
    PassFxn(std::bind(&X::StaticMemberDoIt, _1, _2, _3)); 
    

    // ...and you can basically pass any callable object!
}

Aucun commentaire:

Enregistrer un commentaire