映射中的任何类型的值

Any type of value in map

本文关键字:类型 任何 映射      更新时间:2023-10-16

我执行了以下代码:

#include <string>
#include <map>
#include <vector>
typedef std::map<std::string, std::map<std::string, std::map<std::string, std::string> > > SCHEMA;
int main() {
    SCHEMA tables;
    // Schema table
    tables["table_name"]["row_id"]["field_name"] = "value";
}

我想修改typedef,使其具有一个"row_id"作为数字索引和任何类型的值(某种自动检测)。我应该做些什么来实现这样的目标?

tables["table1"][0]["field1"] = "value of any type";

数字索引很简单,只需将std::string替换为int即可。"任何类型的值"可能很难获得正确的C++,如果不小心,可能会导致问题。您可以使用void *(坏)或union(好),但更好的选择可能是一些变体实现,例如boost::variant,因此typedef将读取,例如:

typedef std::map<std::string, std::map<int, std::map<std::string, boost::variant<int, std::string> > > > SCHEMA;