泛型和非泛型顶点类型的图形类



已经讨论了具有可选数据字段的顶点类 按需跳过通用参数;对我来说最好的解决方案是这样的:

type
TVertex = class
public
Name: String;
OutputAttributes: TVertexOutputAttributes;
Marker: Boolean;
end;

type
TVertex<T> = class(TVertex)
public
Data: T; // User-defined data attribute
end;

在现在编写连接的图类时,我想出了另一个问题:

TGraph = Class
private
Vertices: TObjectList<TVertex>;
....
function addVertex(u: TVertex): Integer;
function removeVertex(u: TVertex): TVertex;
end;

所有函数现在都请求我的顶点类 Tvertex 的非通用版本。 扩展我的 Graph 类以使用两个顶点类定义(通用顶点和非泛型 TVertex )的最佳方法是什么? 我尝试了以下代码但没有成功。

//  a generic class working with 2 Tvertex class definitions ... 
//  this code does npot work :-(  
TGraph<MyVertexType> = Class
private
Vertices: TObjectList<MyVertexType>;
....
function addVertex(u: MyVertexType): Integer;
function removeVertex(u: MyVertexType): MyVertexType;
end;

您当前的代码将无法编译,因为您使用TObjectList<T>这要求T是一个类。没有任何约束可以强制这样做。因此,您可以添加该约束:

type
TGraph<MyVertexType: class> = class
FVertices: TObjectList<MyVertexType>;
...
end;

我确实想知道您是否已经充分考虑了顶点的终身所有权。使用TObjectList<T>意味着您希望列表拥有对象,并在从列表中删除对象时销毁它们。在这种情况下

function removeVertex(u: MyVertexType): MyVertexType;

没有意义。

请注意,上面的定义不允许图类了解MyVertexType的功能,除了它是一个类的事实。因此,也许您应该将MyVertexType限制为顶点:

type
TGraph<MyVertexType: TVertex> = class
...
end;

这将允许图形容器在其成员上调用顶点方法。

type
TVertex = class
public
Name: String;
OutputAttributes: TVertexOutputAttributes;
Marker: Boolean;
end;
TIntVertex = class(TVertex)
public
Data: Integer;
end;
TSomethingElseVertex = class(TVertex)
public
Data: TSomethingElse;
end;
TGraph = class(TObjectList<TVertex>)
// any additional methods
end;

var
Graph: TGraph;
Vertex: TVertex;

Vertex := TIntVertex.Create;
Graph.Add(Vertex);
Vertex := Graph.Last;
if (Vertex is TIntVertex) then
(Vertex as TIntVertex).Data := 42;

最新更新