Is there a way to determine if a function is overridden?

Suppose we have an abstract base class that inherits:

class Base
{
    protected:
        Base() {}
        virtual ~Base() {}
        virtual void on_event_foo(int) {}
        virtual void on_event_bar(int) {}
};

struct Concrete : public Base
{
        virtual void on_event_foo(int value) {/*do some stuff with @value*/}
};

Could this find out (at the time of compilation it would be better) of a function virtualfrom Basethat was overridden (with some code in the constructor or with a special template)?

My goal is to implement a wrapper for a library using some callbacks; and if I can test the overriden functions, I will only create the callbacks that the user wants.

, , . . virtual , .

Base Base C API. -. , static Base::EventFoo(/* ... */), object->on_event_foo(/* .. */). , - C. . , , , .. , .

+4
2

, , ,

#include <iostream>

template <class Derived>
struct Base
{
    virtual void on_event() {}

    void raise_event()
    {
        if (&Derived::on_event == &Base::on_event)
            std::cout << "not overridden" << std::endl;
        else
            std::cout << "overridden" << std::endl;
    }
};

struct Concrete1 : Base<Concrete1>
{
    virtual void on_event() override {}
};

struct Concrete2 : Base<Concrete2>
{
    // no override
};

int main()
{
    Concrete1 c1;
    Concrete2 c2;

    c1.raise_event(); // prints overridden
    c2.raise_event(); // prints not overridden

    return 0;
}

&Derived::on_event == &Base::on_event ( ), if .

, . , .

+6

virtual . , Concrete, -, .

, &T::func . , . , :

template <class T>
void setup_cbs(T& object) {
    T* ptr_to_object = ...; // store somewhere

    static_if<has_on_event_foo<T>>(
        [](auto ptr){ 
            add_event_foo_callback(ptr, [](void* p, int i) {
                using U = decltype(ptr);
                static_cast<U>(p)->on_event_foo(i);
            })
        }),
        [](auto ){}
        )(ptr_to_object);

, . , , .

+1

All Articles