簡體   English   中英

通過定義基類來“多態”聲明非專業模板類型的成員的唯一方法是嗎?

[英]Is the only way to “polymorphically” declare a member of a non-specialized template type, by defining a base class?

假設我們有一個模板化的類,

template<typename Type>
class Container {};

當然,我們不能這樣做:

struct Foo
{
    Container _container;
}

但是,如果我們想做類似的事情怎么辦? 這是定義基類的唯一方法,

class ContainerBase {};

template<typename Type>
class Container : public ContainerBase {};

並存儲一個指針,如下所示?

struct Foo
{
    ContainerBase* _container;
}

這很簡單,但是僅出於這個原因而不得不添加基類,這似乎很奇怪,因為看起來編譯器應該具有足夠的信息來暗示一組相關的專業知識。 當然,無論_container需要成為指針,否則Foo都無法解析為靜態大小,但是

struct Foo
{
    Container* _container;
}

也不起作用。

似乎編譯器應該具有足夠的信息來暗示一組相關的專業知識。

不。 模板的專門性完全不相關,只是名稱不同,類型的名稱與運行時操作基本無關。 給定模板的專業化通常共享(主要是)通用接口,但是它們也可能完全不同。

如果要在各專業之間建立聯系,則必須添加基類。 如果它們有很多共同點,那么將功能納入基礎是一個不錯的主意。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM