mercredi 14 septembre 2022

How to store pointers to callback functions with different signatures in an STL container (map

I'm currently in a situation where I want to store function pointers in an std::map<string, func> . Specifically, these functions are callback functions which have different signatures, and importantly they have different return types which is the heart of my problem.

For example:

// callback 1
GstPadProbeReturn callback_1(GstPad *pad, GstPadProbeInfo *info, gpointer u_data);

// callback 2
GstFlowReturn callback_2(GstPad *pad, GstPadProbeInfo *info, gpointer sharedPtr)

// callback 3
void callback_3(GstElement *element, GstPad *pad, gpointer u_data);

/* somewhere else in the code */
std::map<std::string, functionPtr> cb_map;

map["func1", callback_1];
map["func2", callback_2];
map["func3", callback_3];

and so I can pull the callback I want out of the map and connect the callbacks in the code, which with gstreamer can be done in the following way:

gst_pad_add_probe(probe_pad, GST_PAD_PROBE_TYPE_BUFFER, callback_1, NULL, NULL);

The problem here is callback_1 must match a return type as specified by gst_pad_add_probe while other functions can accept void.

I tried several approached but I keep getting stuck at either not being able to store functions of different signatures in std::map or not being able to pass std::function<void> in the calling function.

I tried the following:

template <class F, class... Args>
inline auto FuncWrapper(F &&f) -> decltype(f)
{
  return f;
}

std::map<std::string, std::function<void>()> cb_map;

auto cb1 = FuncWrapper(&callbacks_1);

this->cb_padprobereturn_map.emplace("one", cb1); // doesn't work 
}

Apologies if this is not clear, I wasn't sure how to succinctly explain this problem. I'm also not well versed enough in c++ to use things such as std::variant

Any help is appreciated!

Aucun commentaire:

Enregistrer un commentaire