jeudi 25 janvier 2018

C++ deal with inheritance and type specific callbacks

Hallo guys it try to achieve the following:

I need a structure which enables me to bind callback functions to a publisher or subscriber where the mapping depends on the type and also on another specifier. Problem is in particular the implementation of the mapping function in the BaseClass and of the callbacks in the DerivedClass (but necessary because callbacks and types are specific for every derived class.

class BaseClass
{
 public:
   template<typename T> 
   MapSubscriberToCallback(const size_t& id, const std::unique_ptr<subschriber<T>>& sub)
   {
       //do some stuff
       auto callback = GetCallback(id,sub);
       sub->addCallback(sub);
   };

   template<typename T>
   std::function<void(const char*, const T&)> GetCallbackconst size_t& id, const std::unique_ptr<subschriber<T>>& sub)
   {
      return std::function<void(const char*, const T&)>();
   };
};

class DerivedClass : public BaseClass
{
public:
   void CallBackType1Behavior1(const char* name, const Type1& message)
   {
      //do stuff;
   };

   void CallBackType1Behavior2(const char* name, const Type1& message)
   {
      //do stuff;
   };

   void CallBackType2(const char* name, const Type2& message)
   {
      //do stuff;
   };

 private:
   std::function<void(const char*, const Type1&)> GetCallbackconst size_t& id, const std::unique_ptr<subschriber<Type1>>& sub)
   {
      if(id==1) return std::bind(&DerivedClass::CallBackType1Behavior1, this, _1, _2);
      else return std::bind(&DerivedClass::CallBackType1Behavior2, this, _1, _2);
   }; 

   std::function<void(const char*, const Type2&)> GetCallbackconst size_t& id, const std::unique_ptr<subschriber<Type2>>& sub)
   {
      return std::bind(&DerivedClass::CallBackType2, this, _1, _2);
   };       
};

So this is my approach but the problem is that in c++ the overloaded functions in the derived class are not known in the base class. The approach will work if the MapSubscriberToCallback member is defined in the derived class but the reason for implementing it in the BaseClass is to use it for many other derived classes.

Hopefully someone can help me how to achieve my goal. Perhaps I need a complete other architecture but no idea how this should look like.

Aucun commentaire:

Enregistrer un commentaire