I am working with a specialized graph class, which has a node class and an edge class. In the node class, there is a list of pointers to each edge. Code that uses the graph must be able to see what edges are contained in a node. This is handled by returning a const reference to a list of edge pointers, i.e:
-
const list<Edge*>& Node::getEdges() const {
-
return edges; // list<Edge*>
-
}
-
However, I don't like this because code outside the graph can modify the edges through the edge pointers. So, ideally, I want this:
-
const list<const Edge*>& Node::getEdges() const {
-
return edges; // list<Edge*>
-
}
-
But, this of course won't work because list<const Edge*> is a different type than list<Edge*>. I had been handling this problem with a reinterpret_cast, which theoretically should work fine since list<const Edge*> and list<Edge*> really are the same type, just with different names. However, this violates strict aliasing rules of g++, so I'm concerned that -03 optimized code may not always work.
Does anyone know a creative way of converting a list<A*> to a list<const A*> without using a reinterpret_cast (and without less efficient methods like copying the entire list)?
I was considering creating my own Java-like Iterator that only returns a const version of each object in the list. Although this would work, it seems like overkill. Any suggestions would be appreciated. Thanks.