jeudi 4 mars 2021

Multiple non-static callbacks of C++ member functions

Related items: https://stackoverflow.com/a/29817048/2725742 and Using a c++ class member function as a c callback function, thread safe version

I have found that using the code in the linked answer/below works well. It effectively creates a "static wrapper" to a non-static member function, to be passed as a callback.

#include <stdio.h>
#include <functional>

template <typename T>
struct Callback;
template <typename Ret, typename... Params>
struct Callback<Ret(Params...)> {
   template <typename... Args>
   static Ret callback(Args... args) {
      return func(args...);
   }
   static std::function<Ret(Params...)> func;
};
template <typename Ret, typename... Params>
std::function<Ret(Params...)> Callback<Ret(Params...)>::func;

So I have that bit in a header file and then various classes have code like below. The problem is that when trying to define two such callbacks within the same scope the second overrides the first.

typedef int (*callback_t)(int*,int*);

Callback<int(int*,int*)>::func = std::bind(&myClass::myMethod1, this, std::placeholders::_1, std::placeholders::_2);
callback_t func1 = static_cast<callback_t>(Callback<int(int*,int*)>::callback);      
register_task1_with_library(func1);

Callback<int(int*,int*)>::func = std::bind(&myClass::myMethod2, this, std::placeholders::_1, std::placeholders::_2);
callback_t func2 = static_cast<callback_t>(Callback<int(int*,int*)>::callback);      
register_task2_with_library(func2);

The callback registered first is redirected to the second. What is the minimal change to create a second "static wrapper" for something like this?

Aucun commentaire:

Enregistrer un commentaire