Basically while trying to implement a graph through adjacency list, I get stucked defining a graph node:
template <
typename Vertex,
typename Edge,
typename EdgeLink = std::pair< Edge, GraphNode* >,
typename Alloc = std::allocator< EdgeLink >
>
class GraphNode
{
public:
Vertex vertex;
std::list< EdgeLink, Alloc > neighbours;
};
I realize that I can’t give parameters to GraphNode template pointer, because they are not defined yet. My question to c++ templates gurus is: what technique is used in this case?
Thanks.
Precising the allocator does not necessitate to precise what the allocator can be used for. For example, in a
std::list<T>the allocator passed isstd::allocator<T>and yet thelistwill allocate_ListNode<T>(implementation defined). This is because allocators need to provide arebindmechanism.In action at ideone.
Note that even though
listwill do arebinditself, you should still do it, because the allocator typesreferenceandpointer(and their const version) will be pulled astypedefinside thelist.EDIT: Allow container specification.
This is tricky because the allocator is unfortunately only defined once you are within
GraphNode, you thus need to pass it to the container only within the class, and thus cannot use it in the template outside.This means using template template parameters, and we thus need to “fix” the arity. Since both
vectorandlistonly take two parameters we are lucky here, but it might not always hold… fortunately with C++11 allowing template aliases, it won’t be too harsh a requirement for the user.This can be invoked so:
Demo.