vendredi 29 juillet 2022

C++ Conversion operator with multiple inheritance

Consider this case with multiple (implementation) inheritance with mixin pattern:

#include <string>
#include <iostream>

template <typename... Bases>
struct Overloads : public Bases... {};

struct Human {};

struct Animal {};

struct Named {
  std::string name_;
  void setName(const std::string& name) {
    name_ = name;  
  }
  const std::string& getName() const noexcept { return name_; }
};

template <typename OverloadsType>
struct Actor : public OverloadsType {

  Actor() : OverloadsType() {}

  template <typename OtherOverloads>
  Actor(const Actor<OtherOverloads>& other_actor) {
      // ???????
      this->setName(other_actor.getName());
  }

};

int main() {
    Actor<Overloads<Human, Named>> named_human;
    named_human.setName("Bob");
    std::cout << named_human.getName() << '\n';
    Actor<Overloads<Animal, Named>> named_animal;

    Actor<Overloads<Animal, Named>> animal_once_a_human (named_human);
    std::cout << animal_once_a_human.getName() << '\n';    
}

The code works correctly, printing two Bobs: Link

I want two things

  1. Make the conversion operator compiles even when OverloadsType and OtherOverloads aren't derived from Named (this->setName(other_actor.getName()); should be ignored or not compiled at all)

  2. Generalize "transferring" information from (common) base classes, not only name

How can I do this?

Aucun commentaire:

Enregistrer un commentaire