[英]Multiple vectors with different types
我正在嘗試創建一個使用表存儲數據的小型概念驗證數據庫系統。 “表”是列的集合。 每列可以具有不同的類型。 每個表可以具有任意數量的列。
理想情況下,我想要類似的東西:
class Table {
map<string, vector<T>> cols; //string is name of col, vector holds data
}
但是,必須在編譯時知道向量的類型,因此在同一映射中不能有多種類型(向量int,向量double等)。
我需要:
class Table {
map<string, vector<int>> int_cols;
map<string, vector<double>> double_cols;
//etc...
}
對於我想存儲的每種類型?
我覺得必須有一個更好的方法來做到這一點。
實際上,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 :-(");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.