Answer the question
In order to leave comments, you need to log in
How are algebraic data types stored?
I read several articles on Habré, but they are all with a bias in Haskell. I can't figure out how algebraic data types are stored. Here is a piece of C++ code about it.
template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; };
template<class... Ts> overloaded(Ts...) -> overloaded<Ts...>;
using var_t = std::variant<int, long, double, std::string>;
std::vector<var_t> vec = {10, 15l, 1.5, "hello"};
for (auto& v: vec) {
std::visit(overloaded {
[](auto arg) { std::cout << arg << ' '; },
[](double arg) { std::cout << std::fixed << arg << ' '; },
[](const std::string& arg) { std::cout << std::quoted(arg) << ' '; },
}, v);
}
Answer the question
In order to leave comments, you need to log in
en.cppreference.com/w/cpp/utility/variant
At the same time
en.cppreference.com/w/cpp/container/vector
This all means that all memory is allocated only in one place, the elements are stored by themselves, and not by pointers.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question