C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Language support for type erasure

From: Sebastian Wittmeier <wittmeier_at_[hidden]>
Date: Mon, 13 Apr 2026 14:23:50 +0200
And it is still possible to keep the Animal overload beside the new Dog and Cat ones. Fulfilling the requirements not to change its code.     -----Ursprüngliche Nachricht----- Von:Jonathan Wakely via Std-Proposals <std-proposals_at_[hidden]> Gesendet:Mo 13.04.2026 14:13 Betreff:Re: [std-proposals] Language support for type erasure An:C++ Proposals <std-proposals_at_[hidden]>; CC:Jonathan Wakely <cxx_at_[hidden]>; On Fri, 10 Apr 2026, 10:39 Frederick Virchanza Gotham via Std-Proposals, <std-proposals_at_[hidden] <mailto:std-proposals_at_[hidden]> > wrote: In a job interview recently I was given the following code:     #include <iostream>     #include <memory>     #include <string>     struct Animal {       virtual ~Animal() = default;       virtual std::string name() const = 0;     };     struct Cat : Animal {       std::string name(void) const override       {         return "Cat";       }     };     struct Dog : Animal {       std::string name(void) const override       {         return "Dog";       }     };     /* DO NOT CHANGE THE CODE BELOW! */     void print_name(Animal const &a)     {       std::cout << a.name <http://a.name> () << std::endl;     }     int main(void)     {       Cat cat;       Dog dog;       print_name(cat);       print_name(dog);     } I was told to remove the inheritance, but I wasn't allowed to edit code beneath the indicated line.   Or you could just add overloads of print_name taking Cat and Dog which works today and is simple to understand. That's the answer I would hope for if I asked that question.   No std::function, no allocations, no hanging reference captures, no new language features needed. Just clear code.   -- Std-Proposals mailing list Std-Proposals_at_[hidden] https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals

Received on 2026-04-13 12:25:14