2014-01-21 14 views
0

已討論帶可選數據字段的頂點類SKIP GENERIC PARAMETER ON DEMAND;對我來說,最好的解決辦法是這樣的:通用和非通用頂點類型的圖類

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和非通用一個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; 
+0

我不明白這個問題。你是什​​麼意思:*所有函數現在請求我的頂點類的非通用版本*? –

+0

在我看來,你正在尋找一個訪問者模式作爲泛型頂點的處理程序 –

+0

我想最相關的問題是 - 它有什麼問題?當然如果有問題需要解決,那就處於實施層面。如果我們不知道實施是什麼,我們如何提供指導? –

回答

1

您當前的代碼將不能編譯,因爲你用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; 

這將使圖形容器呼籲其成員頂點的方法。

+0

我仍然陷入困境,因爲TGraph = class ...將不允許我通過一個帶有一些添加用戶數據T的頂點類型類的TVertex 程序圖init程序。由於TGraph = class有助於編譯我的東西,所以我將在類設計上創建一個進一步的問題 – Franz

+0

您可以肯定地傳遞一個實例化的'TVertex '。評論中很難做到這一切! –

-1
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; 
+0

-1這個問題是非常具體地涉及到泛型 –