C++17 Polymorphism with std::variant
"Downcast" on Polymorphism with std::variant<> template<typename... Functors> struct Ovld : Functors... { using Functors::operator()...; }; // deduce template arguments from initializers: template<typename... Functors> Ovld(Functors...) -> Ovld<Functors...>; class Circle { private: Coord center; int rad; public: Circle (Coord c, int r); void move (Coord c); void draw() const; Coord getCenter() const; }; class Line { private: Coord from; Coord to; public: Line (Coord f, Coord t); void move (Coord c); void draw() const; }; void drawElems(const std::vector<GeoObjVar>& v) { for (const GeoObjVar& geoobj : v) { std::visit(Ovld{[](const auto& obj) { obj.draw(); }, [](const Circle& c) { c.draw(); std::cout << c.getCenter() << '\n'; } }, geoobj); } } C++17 Features: std::variant<> Aggregates with base classes Deduction guides Variadic using 99 C++17 josuttis.com
Слайд с доклада по C++17 показывает реализацию полиморфизма через std::variant, шаблон Ovld и классы Circle и Line. Шутка основана на том, что вместо привычного наследования и виртуальных методов предлагается сложная шаблонная конструкция с visitor-подходом — типичный «подводный камень» современного C++. EN: A presentation slide about C++17 shows polymorphism implemented with std::variant, the Ovld template, and Circle and Line classes. The joke is that instead of familiar inheritance and virtual methods, it presents a complicated template-and-visitor construction—a typical modern C++ “trap.”
- @ithueti / 828 2019-04-19
- Type
- image
- Size
- 800×600 · 56.1 KiB
- Mood
- ироничный, технический
- Language
- en
- Added