lundi 14 mai 2018

How the base class calls the closure passed by the derived class in c++?

I have a base class, and it have a member function that sometime will be called. Usually, this function have a parameter that pointing to itself.

class Base {

public:
    std::function<bool(Base *, int)> foo;

private:
    int x{};

public:
    static std::shared_ptr<Base> create() {
        return std::make_shared<Base>();
    }

    Base() = default;

    const std::function<bool(Base *, int)> &getFoo() const {
        return foo;
    }

    void setFoo(const std::function<bool(Base *, int)> &foo) {
        Base::foo = foo;
    }

    int getX() const {
        return x;
    }

    void setX(int x) {
        Base::x = x;
    }
};

But when I have a derived class, how can I set this member function? Although the base class pointer can point to a subclass object, but I directly passed into the derived object, the compiler does not pass.

class Derived : public Base {
public:
    static std::shared_ptr<Derived> create() {
        return std::make_shared<Derived>();
    }
};

int main() {
    auto d = Derived::create();
    d->setX(77);
    b->setFoo([](Derived *derived, int x) -> bool { return derived->getX() > x; });

    if (d->getFoo()) {
        auto res = d->foo(d.get(), 99);
        std::cout << res << std::endl;
    }

    return 0;
}

error: no viable conversion from '(lambda at main.cpp:62:15)' to 'const std::function' b->setFoo([](Derived *derived, int x) -> bool { return derived->getX() > x; }); ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

So, is there any good idea to pass a closure to base class, and base class call it instead of derived class, and the most important thing is that closure have a parameter which is point to who pass the closure!

Aucun commentaire:

Enregistrer un commentaire