2
class Animal               { public: virtual void say() const { std::cout << "mew ?\n"; } };
class Lion : public Animal { public: virtual void say() const { std::cout << "roar !\n"; } };
class Autobus              { public: virtual void say() const { std::cout << "vroum !\n"; } };
// 1 client acting on these classes
struct PetSomething {
    void operator()(const Animal& a)  { cout << "It says ";  a.say(); }
    void operator()(const Autobus& a) { cout << "It makes "; a.say(); }
};

int main(void) {
  std::variant<Animal, Autobus> thing; // Declaration of $\textrm{\szif thing}$
  thing = Animal();
  std::visit(PetSomething{}, thing);   // Displays "It says mew ?"
  thing = Autobus();
  std::visit(PetSomething{}, thing);   // Displays "It makes vroum !"
  thing = Lion();
  std::visit(PetSomething{}, thing);   // Displays "It says mew ?"
  thing = 666;                         // Type error          
} 

and I'm wondering what type of polymorphisme we are using here, and why we have this behavior specially here :

thing = Lion();
  std::visit(PetSomething{}, thing);   // Displays "It says mew ?"
François Andrieux
  • 28,148
  • 6
  • 56
  • 87
john wick
  • 21
  • 1

0 Answers0