我已经从 boost::variant 迁移到 std::variant,但遇到了障碍。
我在 boost 'type()' 中使用了一个很好的函数,它可以让你获得当前保存的 typeid。参见 https://www.boost.org/doc/libs/1_48_0/doc/html/boost/variant.html#id1752388-bb
这如何通过 std::variant 实现?
我在“type_index”上有一个无序映射键,它包含一些值“std::function”。根据类型的不同,我的变体将决定我从 map 中获取什么功能来执行某些操作。 (我的代码太大,无法发布)。
除了为特定的 std::variant 编写特定的访问者之外,还有什么实现想法吗?也许在 std::variant 上使用“index()”函数,然后索引到变体的类型列表中?有点像这样:How to get N-th type from a tuple?
最佳答案
template<class V>
std::type_info const& var_type(V const& v){
return std::visit( [](auto&&x)->decltype(auto){ return typeid(x); }, v );
}
或者
template<class...Ts>
std::type_info const& var_type(std::variant<Ts...> const& v, std::optional<std::size_t> idx={}){
if (!idx) idx=v.index();
if(*idx==std::variant_npos) return typeid(void);
const std::array<std::type_info const*, sizeof...(Ts)> infos[]={ &typeid(Ts)... };
return *(infos[*idx]);
}
这让您可以询问其他不活跃的索引。
关于c++ - 获取当前保存的 std::variant 的 typeid(如 boost::variant type()),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53696720/