LearnFrenzy
Sign in Take a free test

Polymorphism and Virtual Functions · Polymorphism Programs · Question 7

Shapes with std::variant and visitors in C++ Solution, output & explanation

  • Program
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

Model circles, squares and triangles as a std::variant (no base class), and write two visitors – one for area and one for a description – then process a list.

Solution
main.cpp
#include <format>
#include <iostream>
#include <numbers>
#include <string>
#include <variant>
#include <vector>

struct Circle   { double r; };
struct Square   { double s; };
struct Triangle { double b, h; };
using Shape = std::variant<Circle, Square, Triangle>;

template <typename... Fs> struct overloaded : Fs... { using Fs::operator()...; };   // combine lambdas

int main() {
    std::vector<Shape> shapes{Circle{1}, Square{3}, Triangle{4, 5}};
    auto area = overloaded{
        [](const Circle& c)   { return std::numbers::pi * c.r * c.r; },
        [](const Square& s)   { return s.s * s.s; },
        [](const Triangle& t) { return t.b * t.h / 2; },
    };
    auto describe = overloaded{
        [](const Circle& c)   { return std::format("circle r={}", c.r); },
        [](const Square& s)   { return std::format("square s={}", s.s); },
        [](const Triangle& t) { return std::format("triangle {}x{}", t.b, t.h); },
    };
    double total = 0;
    for (const auto& s : shapes) {
        double a = std::visit(area, s);
        total += a;
        std::cout << std::format("{:<15}{:>6.2f}\n", std::visit(describe, s), a);
    }
    std::cout << std::format("{:<15}{:>6.2f}\n", "total", total);
    return 0;
}

Output Verified by compiling and running

circle r=1       3.14
square s=3       9.00
triangle 4x5    10.00
total           22.14

The overloaded helper merges lambdas into one visitor. Adding a new operation is just another visitor; forgetting a shape in any visitor is a compile error – the strength of std::variant for closed sets of types.

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links