How to iterate an `std::array` with `std::any` value type?

1.2k views Asked by At

How to iterate an std::array with std::any value type. Suppose we don't use the std::tuple and std::get but only a std::array<std::any, SIZE>.

I have declared it:

std::array<std::any, 5> array_any = {
        "Hello",
        50,
        3.1415926535897l,
        true,
        nullptr
};

I could print like this without a loop:

std::cout
<< std::boolalpha
<< std::any_cast<const char*>(array_any[0]) << ' '
<< std::any_cast<int>(array_any[1]) << ' '
<< std::any_cast<long double>(array_any[2]) << ' '
<< std::any_cast<bool>(array_any[3]) << ' '
<< std::any_cast<std::nullptr_t>(array_any[4]) << '\n'
<< std::noboolalpha; 

The output:

Hello 50 3.14159 true nullptr

How about this?

for (const auto& elem : array_any) {
    std::cout << std::any_cast</* placeholder only */>(elem) << ' ';
}

How can I achieve this thing to print exactly the same as the first one without the help of std::tuple but can use some other vocabulary types such as std::variant and also the power of generic programming? Is it possible?

0

There are 0 answers