简体   繁体   English

具有不同类型的多个向量

[英]Multiple vectors with different types

I'm trying to create a small proof-of-concept database system that uses Tables to store data. 我正在尝试创建一个使用表存储数据的小型概念验证数据库系统。 A "Table" is a collection of columns. “表”是列的集合。 Each column can have a different type. 每列可以具有不同的类型。 Each table can have any number of columns. 每个表可以具有任意数量的列。

Ideally, I'd like something like: 理想情况下,我想要类似的东西:

class Table {
  map<string, vector<T>> cols; //string is name of col, vector holds data
}

However, the type of the vector has to be known at compile time, so I can't have multiple types (vector int, vector double, etc) in the same map. 但是,必须在编译时知道向量的类型,因此在同一映射中不能有多种类型(向量int,向量double等)。

Do I need: 我需要:

class Table {
  map<string, vector<int>>    int_cols;
  map<string, vector<double>> double_cols;
  //etc...
}

For each type that I'd like to be able to store? 对于我想存储的每种类型?
I feel like there has to be a better way to do this. 我觉得必须有一个更好的方法来做到这一点。

Actually C++ is not the best choice to manage dynamic types. 实际上,C ++不是管理动态类型的最佳选择。 Consider this member of vector: 考虑向量的这个成员:

reference operator[](size_type index);

If the type is not statically resolved, how will the return value be interpreted under binary level? 如果类型不是静态解析的,那么如何在二进制级别解释返回值? For a language lack of meta class info support, there is no elegant universal solution for such a problem. 对于缺少元类信息支持的语言,没有完美的通用解决方案来解决此类问题。 However, if the types of the values you intend to store are enumerable, I may suggest you to try boost::any or boost::variant: 但是,如果您打算存储的值的类型是可枚举的,我建议您尝试使用boost :: any或boost :: variant:

map<std::string, boost::any> cols;

It really looks bad when you have to fetch a value: 当您必须获取值时,它看起来确实很糟糕:

if (cols[key].type() == typeid(std::vector<int>)) {
    process(cols[key].any_cast<std::vector<int>>());
} else if (cols[key].type() == typeid(std::vector<double>)) {
    process(cols[key].any_cast<std::vector<double>>());
}
...
} else {
    throw std::runtime_error("Oops! Seems that I missed a type :-(");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM