vendredi 24 mars 2023

Compile Time Interface

I am just wondering, is it a bad practice to use the below pattern for writing interfaces in C++? I recently came across a code base that uses this. Any advantages or disadvantages of using this? Is there a name for this pattern?

template<class Impl>
class Interface {
private:
  Impl impl_;
public:
  
  template<class... Args>
  Interface(Args&&... args) : impl_(std::forward<Args>(args)...){ }

  void foo(){
    impl_.foo();
  }

  void foo_bar(){
    impl_.foo_bar();
  }
}

class Impl1 {
private:
  int x_;
  std::string y_;
public:

  Impl1(int x, std::string y) : x_(x), y_(y){}

  void foo(){
    ...
  }

  void foo_bar(){
    ...
  }
}

class Impl2 {
private:
  int x_;
public:

  Impl2(int x) : x_(x){}

  void foo(){
    ...
  }

  void foo_bar(){
    ...
  }
}

int main {

  auto impl_1 = Interface<Impl1>(1, "whatever");
  auto impl_2 = Interface<Impl2>(2);
  return 0;
}

Aucun commentaire:

Enregistrer un commentaire