Store Circle, Rect and Triangle structs (no base class) in a vector of std::variant, and compute area and perimeter with std::visit and a generic lambda that calls member functions.
Solution
main.cpp
#include <cmath>
#include <format>
#include <iostream>
#include <numbers>
#include <variant>
#include <vector>
struct Circle { double r; double area() const { return std::numbers::pi * r * r; } double perimeter() const { return 2 * std::numbers::pi * r; } const char* name() const { return "circle"; } };
struct Rect { double w, h; double area() const { return w * h; } double perimeter() const { return 2 * (w + h); } const char* name() const { return "rect"; } };
struct Triangle { double a, b, c; double area() const { double s = (a + b + c) / 2; return std::sqrt(s * (s - a) * (s - b) * (s - c)); }
double perimeter() const { return a + b + c; } const char* name() const { return "triangle"; } };
using Shape = std::variant<Circle, Rect, Triangle>;
int main() {
std::vector<Shape> shapes{Circle{1}, Rect{3, 4}, Triangle{3, 4, 5}};
double total = 0;
for (const auto& s : shapes) {
std::visit([&total](const auto& x) {
std::cout << std::format("{:<9}area {:>6.2f} perimeter {:>6.2f}\n", x.name(), x.area(), x.perimeter());
total += x.area();
}, s);
}
std::cout << std::format("total area {:.2f}\n", total);
return 0;
}
Output Verified by compiling and running
circle area 3.14 perimeter 6.28
rect area 12.00 perimeter 14.00
triangle area 6.00 perimeter 12.00
total area 21.14
A generic lambda works for every alternative because they all offer the same member functions – static polymorphism without inheritance.
More Modern C++ Features (C++11 to C++23) practice questions
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!