Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create std::variant from another with a sub set of the types

Seen some other questions about this but they so not seem to be answered correctly or there is no answer at all.

I have a instance of a std::variant and I want to create another instance with a sub set of the types in the first one as I know the original is not that type. For exmaple…

std::varaint<int, const char*, bool> v1 = false;
std::varaint<int, bool> v2 = cast_variant<int, bool>(v1);

As you can see I can guarantee v1 does have a value that is in the list of types for v2. Just wondering how you would implement this or can you?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

you can use std::visit to get the item, then create new std::variant from it

template <typename...Ts, typename...Us>
std::variant<Ts...> cast_variant(const std::variant<Us...>& variant){
    return std::visit(
        [&](auto&& v)->std::variant<Ts...>{
            // or you can check if type of v inside Ts... 
            if constexpr(requires {std::variant<Ts...>{v};}) 
                return v;
            else
                throw std::bad_variant_access();
        }
        ,variant
    );
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading