I'm just porting some code from javascript to C++. As some might know, in JS it's pretty ususal to buffer callbacks in a vector, but how can I do the same in C++?
Consider the following - not yet working - code. What I'm doing here is for an object tree
to register a callback with its leaf
(sorry couldn't think of better names). As the callback function will access members within tree
itself, it needs to capture the this-pointer. The problem that arises now is twofold:
The leaf class layout needs to be known, therefore I need to provide the type of the callable to the vector. But it's impossible to know the type of a lambda beforehand, especially if it catches the this ptr.
Even if the type could be deduced beforehand, I still have the problem that the lambda type would probably only allow this-pointers of a specific object to be embedded into its type, thus rendering every call to
register_callback()
that doesn't originate fromtree
as unavailable.
#include <vector>
#include <cstdio>
template <std::invocable Cb>
class leaf
{
public:
auto register_callback(Cb)
{
}
auto do_leave()
{
for (auto cb : callbacks_) {
cb();
}
}
std::vector<Cb> callbacks_;
};
class tree
{
public:
tree()
{
myleaf_.register_callback([this](){
do_some_messageing();
});
}
auto do_some_messageing() -> void
{
printf("Hello World\n");
}
leaf<???> myleaf_;
};
int main()
{
tree Tree1;
Tree1.myleaf_.do_leave();
}
What would I have to do to circumvent those problems? If possible without std::function. I'm also open for different approaches.