jeudi 13 juillet 2023

C++ template specialization depending of Enum value [closed]

I have a class with a templated method taking several type of data. Depending of enum value, this class call several listeners. Currently I shall propagate the types into the listeners even if they does not use the data.

In each listener I want to have only methods for the data it needs.

I want to specialize template depending of an enum value: Something like this:

struct FooA{};
struct FooB{};

enum class Listener_T : int8_t
{
   E_1,
   E_2
};

struct ListenerA
{
   void doSpecificToA(FooA value){};
};

struct ListenerB
{
   void doSpecificToB(FooB value){};
};

struct Generic
{
   ListenerA lstA;
   ListenerB lstB;

   template <typename Data, Listener_T Enum>
   typename std::enable_if<(Enum == Listener_T::E_1) && (std::is_same<Data, FooA>::value), void>::type doSomething(Data data, Listener_T enumLst)
   {
      lstA.doSpecificToA(data);
   };

   template <typename Data, Listener_T Enum>
   typename std::enable_if<(Enum == Listener_T::E_2) && (std::is_same<Data, FooB>::value), void>::type doSomething(Data data, Listener_T enumLst)
   {
      lstB.doSpecificToB(data);
   };



   template<typename Data>
   void doOnData(Data data, Listener_T enumLst)
   {
      doSomething(data, enumLst);
   }
};


int main()
{
FooA a;
FooA b;
Generic g;

g.doOnData(a, Listener_T::E_1);
g.doOnData(b, Listener_T::E_2);


}

thanks

Aucun commentaire:

Enregistrer un commentaire