Suppose I have a Shape
base class and Circle
, Line
, and Point
derived classes. I have two functions.
std::variant<Circle, Line, Point> process(const Shape &s);
Shape process(const Shape& s);
I can pass in any of my derived classes and return a Shape object in the second function, a variant is just a union that can hold any of my derived class variables at any given time.
Now with std::variant
I can also employ a visitor
where I can process some function depending on what type my variant is currently holding (I could just create a function object and pass it std::transform
and apply it to each of my objects). However, I can just make that function virtual
in my base class and have each derived class implement it.
So, is variant
just a convenience?
std::variant
's template arguments must share a common base. You can store unrelated types in anstd::variant
. – HeartburnCircle
and aRectangle
polymorphically, unless they both inheritShape
, thats a small but big difference – Heighhostd::variant<int,double,std::string>
, no chance to get anywhere close to that via inheritance – HeighhoShape process(const Shape& s)
isn't the same asstd::variant<Circle, Line, Point> process(const Shape &s)
as the former slices the object. You need to return by reference/smart pointer/pointer. – Includedstd::variant<int,double,std::string>
anymore. – Includedstd::variant
– Ridgley