mercredi 15 novembre 2023

Variadic template and perfect-forward question

Let's say we have 2 concrete classes.
Both of them can operate, but with different type of parameters (length & type). I want to make a generic operate:

class ServiceA
{
public:
  void operate();
}

class ServiceB
{
public:
  void operate(int, float);
}

class ServiceManager
{
public:
  enum class ServiceType {A, B};
  ServiceA sa;
  ServiceB sb;

  // pseudo-code
  template<typename... Ts>
  void operate(ServiceType t, Ts... args)
  {
    if (t == ServiceType::A)
      sa.operate();
    else if (t == ServiceType::B)
      sb.operate(std::forward<Ts>(args)...);
  }
}

ServiceManager sm;
sm.operate(ServiceType::A);          // sm.sa.operate()
sm.operate(ServiceType::B, 0, 1.0);  // sm.sb.operate(0, 1.0)

Questions:

  • Is this possible by using variadic template + perfect forwarding?
  • Is this program ill-formed? If so, how to deal with the "manager class + same operate but different params" problem?

Aucun commentaire:

Enregistrer un commentaire