I’ve coded up a templated digraph class (Graph<Generic>) for use with Djikstra’s in a project I’m working on. In it, it allocates memory for a DataContainer object that is initialized with an AdjacencyList instance (which implements IDataContainer) for keeping track of all the nodes and edges. I’ve also coded up an AdjacencyMatrix class (which also implements IDataContainer) that I’d like the option of dynamically using in some cases.
Right now I create a digraph with the following call:
Graph<string> graph = new Graph<string>();
And in my graph, I create my data container with:
IDataContainer<Generic> data;
public Graph()
{
data = new AdjacencyList<Generic>();
}
Ideally, I’d like to pass in the data structure I’d like to use (List vs. Matrix) when I call the constructor, like:
Graph<AdjacencyMatrix, string> graph = new Graph<AdjacencyMatrix, string>();
But I’m not quite sure how to pass in a type that’s been templated. I can template it in such a way to allow a call like:
Graph<AdjacencyList<string>, string> graph = new Graph<AdjacencyList<string>, string>();
But when I go to create the AdjacencyList in the class (where public class Graph<Container, Generic> where Container : new() with the where clause as per http://msdn.microsoft.com/en-us/library/x3y47hd4(v=vs.80).aspx) with:
data = new Container();
I get the error:
Cannot implicitly convert type 'Container' to 'GraphDataContainer<Generic>'. An explicit conversion exists (are you missing a cast?)
I could probably include an implicit typecast that would solve the error, but I think the fact that there’s an error at all when trying to create the instance (when passing in a child class to GraphDataContainer) shows that there’s something else wrong here. Is it my inheritance, or is it something convoluted in the messy constructor call (which, if you can think of a cleaner way to do, would be much appreciated!)?
Is there a way to tell a class which class to use to manage its data when it is initially constructed?
What about
Then you can use
and in the
GraphclassThis could be also accomplished with interfaces
For example, consider the
Graphclass contructor. You could make something like:and have
AdjacentListandAdjacentMatriximplementIContainer.