Consider the following code (run it)
#include <fmt/core.h>
#include <string>
#include <array>
#include <variant>
struct Student {
std::string name;
Student(const char* name) : name(name) {}
void display() { fmt::print("Student {}\n", name); }
virtual play() { fmt::print("Student {} played\n", name); }
};
struct Teacher {
std::string name;
Teacher(const char* name) : name(name) {}
void display() { fmt::print("Teacher {}\n", name); }
virtual play() { fmt::print("Teacher {} played\n", name); }
};
int main() {
// case 1: use Student
Student student{"Alice"};
student.display();
// case 2: use std::variant which holds a Student
std::variant<Student, Teacher> person(std::in_place_type<Student>, "Charlie");
std::visit([](auto&& arg) {
arg.display();
}, person);
}
What is the cost of case 2 comparing to case 1?
Does it only need to identify the type (using some saved index) and then do a reinterpret_cast
like operation and then invoke the display
member function?
Another question as raised by @alfC: if I change the above main
to call play
instead of display
, which is a virtual function, will the cost be different?