Created
November 5, 2023 15:49
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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