【问题标题】:Multiple vectors with different types具有不同类型的多个向量
【发布时间】:2016-02-01 22:27:11
【问题描述】:

我正在尝试创建一个小型概念验证数据库系统,该系统使用表来存储数据。 “表”是列的集合。每列可以有不同的类型。每个表可以有任意数量的列。

理想情况下,我想要这样的东西:

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

但是,向量的类型必须在编译时知道,所以我不能在同一个映射中有多种类型(vector int、vector double 等)。

我需要吗:

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

对于我希望能够存储的每种类型?
我觉得必须有更好的方法来做到这一点。

【问题讨论】:

  • 一个Column基类怎么样,派生IntColumnMarineMammalColumn等,而Table包含一个vector&lt;Column*&gt;
  • 你能看看Type Erasure吗?
  • 可能类似于this

标签: c++ vector


【解决方案1】:

实际上,C++ 并不是管理动态类型的最佳选择。考虑向量的这个成员:

reference operator[](size_type index);

如果类型不是静态解析的,那么二进制级别下返回值如何解释?对于缺乏元类信息支持的语言,对于这样的问题没有优雅的通用解决方案。但是,如果您打算存储的值的类型是可枚举的,我可能会建议您尝试 boost::any 或 boost::variant:

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

当你必须获取一个值时看起来真的很糟糕:

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 :-(");
}

【讨论】:

    猜你喜欢
    • 2018-05-05
    • 1970-01-01
    • 2012-08-17
    • 1970-01-01
    • 2019-08-31
    • 1970-01-01
    • 2016-03-17
    • 2023-03-28
    • 1970-01-01
    相关资源
    最近更新 更多