模板vs虛函式

2021-04-01 21:47:36 字數 1376 閱讀 3315

考慮如下兩個容器的定義:

template

class

math_container

const t& operator (size_t i) const

bool

operator==(const math_container& a) const

};template

class

music_container

const t& operator (size_t i) const

bool

operator==(const music_container& a) const

};兩個類的operator==是一樣的,沒有必要存在兩份完全一樣的定義,所以應該抽取出來放在共同的基類中,然而基類operator==的實現依賴於派生類的某些成員函式,解決這種問題的典型做法是使用虛函式:在基類中定義虛函式,在派生類中改寫。

template

class

basic_ops

};template

class

math_container : public basic_ops

const t& operator (size_t i) const

};template

class

music_container : public basic_ops

const t& operator (size_t i) const

};但是虛函式有乙個最大的問題

:被呼叫的函式只有在執行期間才能確定下來。如果能在編譯期間就確定下來,執行速度肯定會有所提高。為了做到這一點,基類必須知道派生類的型別資訊,這一點可以通過將派生類的型別作為模板引數傳遞給基類來實現。

template

class

basic_ops

bool

operator==(const c& a) const

};template

class

math_container : public basic_ops>

const

t& operator (size_t i) const

};template

class

music_container : public basic_ops>

const t& operator (size_t i) const

};就是這樣。

模板 虛函式

按我的閱讀和設計經驗,乙個體繫結構如果要用模板,那麼這個體系裡應該全都是模板,如果實在要公開某些虛基類,一般在模板繼承鏈中最底層 最後派生層 實現基類函式 除非有特殊需求 但前提是這個虛基類的成員引數不能是模板。在模板世界裡,虛函式除了增加虛表大小和降低執行效能,沒有實際意義。stl atl wtl...

模板類 虛函式

1 class faux27 8910 template 11 class vrai 1216 為什麼 faux 中不行呢?因為如果 virtual function 是 template 的,根據使用的不同型別,class faux 會有很多 do do,do.而 c 要求在 faux 記憶體布局...

模板類可以使用虛函式,模板函式不能是虛函式

1 普通的類中怎麼使用虛函式,模板類中也可以這麼使用虛函式 不過需要注意的是使用模板類定義不同的型別則是兩個完全不同的類。2 模板函式不能是虛函式 編譯器期望在處理類定義的時候就能確定虛函式表的大小,如果允許有類的虛成員模板函式,那麼就必須要求編譯器提前知道程式中國有對該類的該虛成員模板函式的呼叫,...