B
B
beduin012018-03-29 18:37:56
C++ / C#
beduin01, 2018-03-29 18:37:56

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);
}

As I understand it, some kind of container (variable) is created in which pointers to elements in the heap are placed, which can be predefined types (otherwise - an error). I understand correctly?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2018-03-29
@zagayevskiy

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 question

Ask a Question

731 491 924 answers to any question