使用模板的一个指针向量中的多种数据类型

Multiple data types within one vector of pointers using templates

下面有两个类,

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>*, ...}

我建议你使用多态并创建一个非模板基础class:

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;
}

有了这个基础 class,您的 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