ev-drogon-any-view-data-typecheck-002¶
| 字段 | 值 |
|---|---|
| 项目 | drogonframework/drogon |
| 固定 commit | 3aae769cc405 |
| 路径 | lib/inc/drogon/HttpViewData.h |
| 行段 | L40-L53 |
| 特性 | std::any |
| 许可证 | MIT |
| 代码来源 | 项目源码 |
| 级别 | manual |
| 审核 | zyuhao7 @ 2026-10-25 |
| 测试代码 | 否 |
| 发现方式 | tree-sitter |
用法¶
读取前比较 typeid,再用 any_cast 指针形式取地址
为什么典型¶
std::any 只做精确类型匹配;先用 type() 判断再转换,可以避免 bad_any_cast,并在类型不符时记录错误而不是终止请求。
摘录¶
static const T nullVal = T();
auto it = viewData_.find(key);
if (it != viewData_.end())
{
if (typeid(T) == it->second.type())
{
return *(std::any_cast<T>(&(it->second)));
}
else
{
LOG_ERROR << "Bad type";
}
}
return nullVal;
备注¶
生产路径;模板函数返回 T,类型不匹配时回退到默认值。