我在现代 C++ 中遇到过各种容器库,它们找到了一种方法来覆盖 operator[]
并仍然返回多种类型。例如,使用 nlohmann::json ,下面的代码都是有效的:
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"];
这怎么可能,尤其是在案例中?在我自己的尝试中,我遇到了“无法推断‘T’的模板参数”的常见错误情况。我确实认为它与某些代理对象(可能是 value_t
或 object_t
)有关,但是在这种情况下我无法深入跟踪模板逻辑nlohmann 的 json 实现(令人印象深刻!)。
最佳答案
如果您查看 nlohmann::json::operator[]
的声明,它会返回一个 reference
,它被定义为一个 value_type&
,其中 value_type
定义为 basic_json
。 basic_json
类有一个模板化的转换运算符,可以将 json 值转换为 basic_json::get()
方法支持的任何类型,包括 bool 值、整数、字符串、等等。所以,您实际上在做的是:
//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>();
关于c++ - 一些库如何用多个返回类型覆盖 operator[]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53490063/