qdtang
qdtang

Reputation: 31

std::bind with overloaded function from parent class

#include <iostream>
#include <functional>

class Base
{
    public:
        virtual ~Base() {}
        virtual void f1() const {std::cout<<"Base::f1() called"<<std::endl;}
        virtual void f1(int) const {std::cout<<"Base::f1(int) called"<<std::endl;}
        virtual void f2() const {std::cout<<"Base::f2() called"<<std::endl;}
};

class Derived : public Base
{
    public:
        virtual ~Derived() {}
        void f1() const {std::cout<<"Derived::f1() called"<<std::endl;}
};

int main()
{
    Base base;
    Derived derived;
    auto func1 = std::bind(static_cast<void(Base::*)()const>(&Base::f1), std::cref(base));
    func1();
    auto func2 = std::bind(static_cast<void(Derived::*)()const>(&Derived::f1), std::cref(derived));
    func2();
    auto func3 = std::bind(&Base::f2, std::cref(base));
    func3();
    auto func4 = std::bind(&Derived::f2, std::cref(derived));
    func4();
    auto func5 = std::bind(static_cast<void(Base::*)(int)const>(&Base::f1), std::cref(base), std::placeholders::_1);
    func5(1);
    auto func6 = std::bind(static_cast<void(Derived::*)(int)const>(&Derived::f1), std::cref(derived), std::placeholders::_1);  // error line
    func6(2);
    return 0;
}

When I try to build above code, gcc gives following error message.

test.cpp:34:80: error: invalid static_cast from type ‘void (Derived::)() const’ to type ‘void (Derived::)(int) const’

auto func6 = std::bind(static_cast(&Derived::f1), std::cref(derived), std::placeholders::_1);

I'm wondering if there is any method with which I can bind Base::f1(int) via class Derived (bind func6 successfully here). Any help is appreciated.

Upvotes: 3

Views: 1869

Answers (1)

max66
max66

Reputation: 66200

What about using &Derived::Base::f1 instead &Derived::f1 ?

I mean

auto func6 = std::bind(static_cast<void(Derived::*)(int)const>(&Derived::Base::f1), std::cref(derived), std::placeholders::_1); 

As suggested by Oktalist (thanks), you can also use &Base::f1.

It's even simpler.

Upvotes: 2

Related Questions