1 Star 8 Fork 2

Gitee 极速下载/reflect-cpp

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
此仓库是为了提升国内下载速度的镜像仓库,每日同步一次。 原始仓库: https://github.com/getml/reflect-cpp
克隆/下载
object.md 2.20 KB
一键复制 编辑 原始数据 按行查看 历史

rfl::Object

rfl::Object<...> behaves similarly to std::map<std::string, ...> and std::unordered_map<std::string, ...>.

It will be represented in JSON or other formats as an object:

auto bart = rfl::Object<std::string>();
bart["first_name"] = "Bart";
bart["last_name"] = "Simpson";
bart["town"] = "Springfield";

This is results in the following JSON string:

{"first_name":"Bart","last_name":"Simpson","town":"Springfield"}

It supports almost all of the normal features you would expect from such a container. For instance, you can iterate through it just like any other map:

for (const auto& [k, v]: bart) {
    std::cout << k << ": " << v << std::endl;
}

However, unlike these containers, the order of fields is preserved. It is also possible to have duplicate keys:

auto bart = rfl::Object<std::string>();
bart["first_name"] = "Bart";
bart["last_name"] = "Simpson";
bart["town"] = "Springfield";

// Note that you need the .insert(...) method,
// because operator[] would overwrite the
// existing field.
bart.insert("first_name", "Lisa");

This results in the following JSON string:

{"first_name":"Bart","last_name":"Simpson","town":"Springfield","first_name":"Lisa"}

There are three different ways of inserting fields:

  • operator[...] creates a new field, if a field of this name doesn't already exist, and then assigns it.
  • .insert(...) inserts a new field at the end, potentially creating duplicate field names. Much like std::map, it supports several types of inputs:
    • .insert(std::pair(key, value))
    • .insert(key, value)
    • .insert(begin, end), where begin and end are iterators of a container of key-value-pairs
  • .emplace(...) is an alias for .insert that exists primarily for reasons of compatability with standard containers.

There are three different ways of accessing fields:

  • operator[...] creates a new field, if a field of this name doesn't already exist.
  • .at(...) throws an exception, if field of this name doesn't exist.
  • .get(...) returns an rfl::Result wrapping the field, or an rfl::Error if the field doesn't exist.

Note that it is most efficient, if you access fields in the order that they were placed.

Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C/C++
1
https://gitee.com/mirrors/reflect-cpp.git
git@gitee.com:mirrors/reflect-cpp.git
mirrors
reflect-cpp
reflect-cpp
f/bit_cast

搜索帮助