简体   繁体   中英

When using variant but error-invoke, could errors happens in compiling time instead of bad_variant_access in running time

If I have a map like

const std::map<int, std::variant<int, std::string>> m ={{1,1},{2,"asd"}};

But if i invoke std::get<string>(m[1]) by mistake instead of std::get<int>(m[1]) , it will raise bad_variant_access. But it is just a typo of codes, so could it be detected by IDE, or some form of static_assert could work because m is a constant(or what if m is not a constant), or raise only compile errors?

If it is always constant, you don't need a map. You can dispatch that at compile time:

#include <iostream>

template <int i>
constexpr auto m() 
{
    if constexpr (i == 1) {
        return 1;
    } else if constexpr (i == 2) {
        return "hello";
    }
}

int main()
{
    std::cout << m<1>() << '\n';
    std::cout << m<2>() << '\n';
}

Or, just use a tuple:

#include <iostream>
#include <tuple>

int main()
{
    std::tuple tuple { 1, "hello world" };
    std::cout << std::get<0>(tuple) << '\n';
    std::cout << std::get<1>(tuple) << '\n';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM