vendredi 24 mai 2019

How to call derived method via function pointer?

Consider this example:

struct base {
    void method() {};
};

struct foo : base {};

template <typename T,typename R>
void call_it(T& t, R (T::*f)()) {
    (t.*f)();
}

template <typename T,typename B,typename R>
void call_it(T& t, R (B::*f)()) {
    (t.*f)();
}    

int main() {
    base b;
    call_it(b,&base::method);
    foo f;
    call_it(f,&foo::method);
}

I was a bit surprised at first that &foo::method is a void (base::*) () not a void (foo::*)(), but then I realized that I can provide the second overload for call_it to enable passing base function pointers together with a reference to a derived object.

Is there a better way to do that? Is the above safe in the sense that it either won't compile or do the right thing?

Aucun commentaire:

Enregistrer un commentaire