Gre*_*ire 4 c++ boost typeid std-variant
我已经从 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”。我的变体,取决于类型,将决定我从地图中抓取什么函数来做一些操作。(我拥有的代码太大而无法发布)。
除了为特定 std::variant 编写特定访问者之外,还有其他实现想法吗?也许在 std::variant 上使用“index()”函数,然后索引到变体的类型列表中?有点像这样:如何从元组中获取第 N 个类型?
template<class V>
std::type_info const& var_type(V const& v){
return std::visit( [](auto&&x)->decltype(auto){ return typeid(x); }, v );
}
Run Code Online (Sandbox Code Playgroud)
或者
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]);
}
Run Code Online (Sandbox Code Playgroud)
这让您可以询问其他不活动的索引。