c++ - 获取当前持有的 std::variant 的 typeid(如 boost::variant type())
问题描述
我已经从 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 );
}
或者
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]);
}
这使您可以询问其他不活动的索引。
推荐阅读
- ios - 我可以为每个 iCloud 获得一个匿名 ID(每个应用程序/用户,而不是每个设备)吗?
- javascript - 反应 | 多语境 | 无法使用默认值
- python - 如何提取数组中的元素?
- ios - UITextView 在应用转换并设置新的类型属性后被剪裁
- php - 在“T”之后使用空格时 php strtotime() 出现意外结果
- enums - Kotlin Enums:引用从它调用的任何 Enum 对象的函数
- sql - 将整数四舍五入到十进制 - SQL
- android - 深层链接仅适用于 GMAIL 应用程序
- bitbucket - 如何在 Bitbucket Pull 请求批准时触发 Jira 中的工单状态更改
- php - curl 错误:libcurl 中不支持或禁用协议“http”