Created
October 17, 2020 16:27
-
-
Save kara-ryli/6b4abc7bda2376d1dd2a54281a0c58c4 to your computer and use it in GitHub Desktop.
I'm still learning the nuances of C and C++; it's a big change from JavaScript. Here's a problem that has such a simple implementation in JS that I never considered the complexity of doing it in C++.
This file contains hidden or 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
// This file represents a simplification of a scope problem I have interacting | |
// with a C SDK. Essentially: | |
// | |
// * I to pass a callback to a C function | |
// * The callback should call a member function of a non-static class instance | |
// | |
// I would like to achieve this without risking memory leaks and crashes, while | |
// also not introducing a huge amount of complexity or rearchitecting the app. | |
#include <iostream> | |
void func(void (*fn)()) | |
{ | |
fn(); | |
} | |
class Thing | |
{ | |
public: | |
void GetMessage() | |
{ | |
std::cout << "Hello World"; | |
} | |
}; | |
// Assume is a non-singleton class instance method, though in practice | |
// only used once, (probably, for now) such that this may appear to work | |
// in a naive implementation even if something is done unsafely. | |
int main() | |
{ | |
// Compiles, but won't fit the use case | |
// func([]() -> void | |
// { | |
// Thing th2; | |
// th2.GetMessage(); | |
// }); | |
Thing th; | |
// Won't compile | |
// auto fn = [&th]() -> void | |
// { | |
// th.GetMessage(); | |
// }; | |
// Won't compile | |
// auto fn = std::bind([](Thing th) -> void | |
// { | |
// th.GetMessage(); | |
// }, th); | |
// Won't compile | |
// std::function<void()> fn = [&th]() -> void | |
// { | |
// th.GetMessage(); | |
// }; | |
// Seems problematic | |
static std::function<void()> staticFunc = [&th]() -> void | |
{ | |
th.GetMessage(); | |
}; | |
auto fn = []() -> void | |
{ | |
staticFunc(); | |
}; | |
// Goal is to call this | |
func(fn); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment