gpt4 book ai didi

c++ - 使用带有 adjacency_list 的通用类型

转载 作者:太空宇宙 更新时间:2023-11-04 12:19:32 25 4
gpt4 key购买 nike

在一个简单的 Graph 项目中使用 Boost 我定义了两种类型的 adjacency_list,一种是有向边,另一种是无向边,如下所示:

typedef adjacency_list < vecS, vertex_distributed_storage, directedS, Node > directedAdjacencyList;
typedef adjacency_list < vecS, vertex_distributed_storage, undirectedS, Node > undirectedAdjacencyList;

*对于此示例,可以忽略 Node 和 vertex_distributed_storage 类型。

到这里一切都还好,但是当我尝试定义接收这些列表之一的函数时,我的问题就来了,因为我可能有一个有向或无向的,这取决于图形类型,所以我需要为我的方法:

void loadGraph(directedAdjacencyList &graph);
void loadGraph(undirectedAdjacencyList &graph);

尽管有重复的函数做同样的事情 :S

我还注意到结构 undirectedSdirectedS 只在一个成员的 bool 上有所不同。

所以我的选项可以为我的函数声明一个泛型类型,这样我就可以给出有向和无向的 adjacency_list,修改前面提到的结构中的 bool 或任何其他可行的想法。

感谢阅读,抱歉我的英语不好。

最佳答案

declare a generic type for my functions so I can give both directed and undirected adjacency_list's

没错。或者,更准确地说,您应该有几个选项来确定您需要的通用程度:

template<typename GraphT>
void loadGraph(GraphT &graph);
// or
template<typename A, typename B, typename C, typename D>
void loadGraph(adjacency_list<A, B, C, D> &graph);
// or
template<typename DirectT>
void loadGraph(adjacency_list < vecS, vertex_distributed_storage, DirectT, Node > &graph);

另请注意,在您的情况下,您可能不需要在 header 中实现 loadGraph,但如果您希望保留 loadGraph< 的代码,则可以在实现文件中添加显式模板特化 出头文件:

// Header File:
template<typename GraphT>
void loadGraph(GraphT &graph);


// Implemenation File:
template<typename GraphT>
void loadGraph(GraphT &graph)
{
// ...
}
// Explicit Template Function instantiations:
template void loadGraph(directedAdjacencyList &graph);
template void loadGraph(undirectedAdjacencyList &graph);

关于c++ - 使用带有 adjacency_list 的通用类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5860801/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com