Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 618
qdtang Avatar asked Mar 19 '26 16:03

qdtang


1 Answers

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.

like image 123
max66 Avatar answered Mar 21 '26 06:03

max66



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!