首页 > 解决方案 > 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!).

标签: c++templates

解决方案


如果查看 的声明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>();

推荐阅读