Aballano
Aballano

Reputation: 1037

Using a generic type with an adjacency_list

Using Boost with a simple Graph project I have defined two type of adjacency_list, one with directed edges and the other with undirected ones like this:

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

*The Node and vertex_distributed_storage types can be ignored for this example.

Until here everything it's okay, but my problem comes when I try to define functions that receives one of these lists because I could have a directed or an undirected one depending on the graph type, so I need to specify a generic type for my methods:

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

Despite of having duplicated functions doing the same stuff :S

I also noticed that the struct undirectedS and directedS only differs in a bool of one member inside.

So my options could be declare a generic type for my functions so I can give both directed and undirected adjacency_list's, modify the bool inside the struct mentioned before or any other idea that works.

Thanks for reading and sorry for my bad english.

Upvotes: 1

Views: 163

Answers (1)

Martin Ba
Martin Ba

Reputation: 38766

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

Exactly. Or, to be more precise, you should have several option on how generic you need to be:

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

Note also, that in your case, you probably do not need to implement your loadGraph in a header, but you can just add explicit template specializations in the implementation file, if you wish to keep the code of loadGraph out of a header file:

// 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);

Upvotes: 1

Related Questions