c++ - How do some libraries override operator[] with multiple return types?
问题描述
I have come across various container libraries in modern day C++ that have found a way to override the operator[]
and still return multiple types. For example, using nlohmann::json, the following code is all valid:
const nlohmann::json settings;
// set some values:
j["pi"] = 3.141;
j["happy"] = true;
// get some values:
std::string deviceName = settings["device"];
bool yesOrNo = settings["blah"];
How is this possible, especially in the case cases? In my own attempts, I've run into the common error case of "could not deduce template argument for 'T'". I do think it has to do with some proxy object (likely value_t
or object_t
), however I haven't been able to follow the template logic back deep enough in the case of nlohmann's json implementation (which is pretty impressive!).
解决方案
如果查看 的声明nlohmann::json::operator[]
,它会返回 a reference
,它定义为 a value_type&
,其中value_type
定义为basic_json
。该类basic_json
有一个模板化的转换运算符,可以将 json 值转换为该basic_json::get()
方法支持的任何类型,包括布尔值、整数、字符串等。所以,您实际上要做的是:
//std::string deviceName = settings["device"];
std::string deviceName = settings["device"].operator std::string();
//which is effectively
//std::string deviceName = settings["device"].get<std::string>();
//bool yesOrNo = settings["blah"];
bool yesOrNo = settings["blah"].operator bool();
// which is effectively
//bool yesOrNo = settings["blah"].get<bool>();
推荐阅读
- javascript - 将 P5js AudioIn 获取到 MediaStream 对象
- sql-server - SQL Server 将 XML 解析为表 - 具有相同名称的多个节点
- python - 按列值连接两个数据框
- python - 资源“00000003-0000-0000-c000-000000000000”上不存在的范围“Mail.ReadBasic.All”
- java - Axon Framework - 我如何回滚 Saga 进程
- apache-nifi - NiFi“架构注册表”无效
- graphql - Apollo graphql:makeExecutableSchema 和游乐场
- c# - 有时 IOrganizationService 对象为空
- javascript - 如何对 observable 上的数据数组进行排序?
- data-science - 预测时如何考虑特征?