Skip to content

Instantly share code, notes, and snippets.

@mjschutz
Created November 5, 2023 15:49
Show Gist options
  • Save mjschutz/269a9885853df5c120bf278d283a88ad to your computer and use it in GitHub Desktop.
Save mjschutz/269a9885853df5c120bf278d283a88ad to your computer and use it in GitHub Desktop.
Wrap a Derived Class method to pass to a closed API call using templated function
#include <iostream>
using namespace std;
struct A {
// Use this to wrap method from a derived class
template <typename Class, void (Class::*method)()>
void makeCall() {
(dynamic_cast<Class*>(this)->*method)();
}
virtual ~A() = default;
};
struct B: public A {
void sayHi() {
cout << "Hi!" << endl;
}
};
void doCall(A& a, void (A::*call)()) { // assumption: a closed API call / method
(a.*call)();
}
int main()
{
B b;
doCall(b, &A::makeCall<B, &B::sayHi>); // this works
// doCall(b, &B::sayHi); // error: cannot convert ‘void (B::*)()’ to ‘void (A::*)()’
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment