lundi 4 octobre 2021

C++ conditional template member function

I am trying to understand how to use std::enable_if to choose between 2 functions implementation. In this case, if the type TupleOfCallback doesn't contains all the type, it will not compile because std::get<...> will throw an error.

For exemple: Executor<Entity1*, Entity2*> task([](Entity1 *e){}, [](Entity2 *2){});

This will not compile because Entity3* is not part of the tuple.

It seem that we can choose between two functions with the same prototype,

void Exec(Entity3 *entity)
{
  //enabled when Entity3* is **not** in the tuple
}

OR

void Exec(Entity3 *entity)
{
  //enabled when Entity3 is in the tuple
  std::get<std::function<void(Entity3*)>>(m_Callbacks)(entity);
}

But i dont understand how to achive this goal.

C++ template mecanisme is still hard for me, any help is welcome.

template<typename ...T>
class Executor
{
  typedef std::tuple<std::function<void(T)>...> TupleOfCallback;
public:
  Executor(const std::function<void(T)> &...func)
  {
  }

  void Exec(Entity1 *entity)
  {
    std::get<std::function<void(Entity1*)>>(m_Callbacks)(entity);
  }

  void Exec(Entity2 *entity)
  {
    std::get<std::function<void(Entity2*)>>(m_Callbacks)(entity);
  }

  void Exec(Entity3 *entity)
  {
    std::get<std::function<void(Entity3*)>>(m_Callbacks)(entity);
  }

public:
    TupleOfCallback m_Callbacks;
};

Thank you for your help.

Aucun commentaire:

Enregistrer un commentaire