Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Calling base class method with std::function

I used std::function for basic class virtual method and had strange result. Then I call std::function object, derived (not basic) method is called. Please, can you tell me there is the problem?

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

struct A
{
    virtual void username(const std::string& name)
    {
        std::cout << "A: username" << name << '\n';
    }

    A* A_ptr()
    {
        return this;
    }
};

struct B : public A
{
    void username(const std::string& name) override
    {
        std::function<void(const std::string&)> f = std::bind(&A::username, A::A_ptr(), std::placeholders::_1);
        wrapper(f, name);
    }

    void wrapper(const std::function<void(const std::string&)>& f, const std::string& s)
    {
        f(s);
    }
};

int main()
{
    B b;
    b.username("tname");
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I don’t think is is possible with std::bind, you can do it with a lambda though:

std::function<void(const std::string&)> f = [this](const std::string& name) {
  A::username(name);
};

By default a member function pointer to a virtual method will use virtual dispatch, to call the base class method you need to use a different syntax which isn’t possible though std::bind

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading