1

How do we create a std::function object for overloaded member functions in a class? std::function object can be created for a non-overloaded member function as shown.

Sample code is attached as shown below

#include<iostream>
#include<functional>

class X
{
    public:
        X(){}
        virtual ~X(){}

        void foo1(char c)
        {std::cout<<"X::foo1(char c)\n";}

        void foo2(char c)
        {std::cout<<"X::foo2(char c)\n";}

        void foo2(int i)
        {std::cout<<"X::foo2(int i)\n";}

}x;

int main()
{
    std::function<void(X*,char)> f1=&X::foo1;
    f1(&x,'a');

    /*  //The following code doesn't work
    std::function<void(X*,char)> f2=&X::foo2;
    f2(&x,'a');
    */

    return 0;
}

Following error is given :

conversion from '' to non-scalar type 'std::function' requested

1 Answers1

1

You need to be explicit about the signature of the overloaded function you intend to use:

std::function<void(X*,char)> f2 = static_cast<void (X::*)(char)>(&X::foo2);

As an alternative, use a lambda:

std::function<void(X*,char)> f3 =
    [](X *instance, char c){ return instance->foo2(c); };
lubgr
  • 37,368
  • 3
  • 66
  • 117