我在下面看到了兩個類,
template <typename T> class node {
public:
int NodeID;//ID used to identify node when inserting/deleting/searching
T data;//generic data encapsulated in each node.
std::vector<node*> children;//child nodes, list of ptrs
std::vector<node*> parents;//parent nodes list of ptrs
};
template<typename T> class DAG {//Class for the graph
std::vector<node<T>*> Nodes;//Vector of node ptrs, this is how we define a DAG;
}
我想知道是否可以使用模板讓節點向量包含多種型別的節點?像這樣的東西。
std::vector<node*> Nodes = {node<int>*,node<string>*, ...}
uj5u.com熱心網友回復:
我建議你使用多型并創建一個非模板基類:
struct nodebase {
nodebase(int id) : NodeID{id} {}
virtual ~nodebase() = default; // to be able to delete via base class pointer
virtual void print(std::ostream& os) const {
os << NodeID;
}
int NodeID; // ID used to identify node when inserting/deleting/searching
std::vector<std::unique_ptr<nodebase>> children; // child nodes, list of ptrs
std::vector<nodebase*> parents; // parent nodes list of ptrs
};
// to be able to print all nodes, calls the overridden `print` method:
std::ostream& operator<<(std::ostream& os, const nodebase& nb) {
nb.print(os);
return os;
}
使用該基類,您node<T>可能看起來像這樣:
template <typename T>
class node : public nodebase {
public:
// constructor taking `id` the arguments needed for `T`:
template<class... Args>
node(int id, Args&&... args) : nodebase{id}, data{std::forward<Args>(args)...} {}
void print(std::ostream& os) const override {
nodebase::print(os);
os << ',' << data;
}
T data; // generic data encapsulated in each node.
};
你可以像這樣使用它:
int main() {
std::vector<std::unique_ptr<nodebase>> Nodes;
Nodes.emplace_back(std::make_unique<node<int>>(1, 12356));
Nodes.emplace_back(std::make_unique<node<std::string>>(2, "Hello world"));
for(auto& ptr : Nodes) {
std::cout << *ptr << '\n';
}
}
輸出:
1,12356
2,Hello world
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/399047.html
下一篇:單擊按鈕時如何使用私人區域的資料
