[英]When using variant but error-invoke, could errors happens in compiling time instead of bad_variant_access in running time
如果我有一個 map 之類的
const std::map<int, std::variant<int, std::string>> m ={{1,1},{2,"asd"}};
但是,如果我錯誤地調用std::get<string>(m[1])
而不是std::get<int>(m[1])
,它將引發 bad_variant_access。 但這只是代碼的錯別字,所以它可以被 IDE 檢測到嗎,或者某種形式的static_assert
可以工作,因為m
是一個常量(或者如果m
不是常量怎么辦),或者只引發編譯錯誤?
如果它始終不變,則不需要 map。您可以在編譯時分派它:
#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';
}
或者,只使用一個元組:
#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';
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.