簡體   English   中英

將 CRTP 與抽象 class inheritance 一起使用是否正確?

[英]Is it correct to use the CRTP along with abstract class inheritance?

在 C++ 中使用抽象 class 的 inheritance 是否正確? 如果是這樣,是否存在與此構造相關的任何潛在問題? 下面給出的代碼片段描述了我的問題。

template<class T>
class Base {
 void method_01() {
  static_cast<T*>(this)->method_01();
 }
};

class AbstractBase {
 virtual void method_02() = 0;
};

class A : public Base<A>, public AbstractBase {

};

是否有任何可能性如何用 CRTP 替換抽象 class inheritance 所以A class 以雙重方式使用 CRTP

class A : public Base_01<A>, public Base_02<A> {

};

就術語而言,具有抽象 class 基礎的問題與 CRTP 垂直,因為 CRTP 描述 inheritance 和 static 多態性,而AbstractBase提供動態多態性

如果不需要類型擦除,可以用 static 替換動態多態性。 CRTP emulates the virtual function call system at compile time without the costs in size or function call overhead, without possible UB or weird code malfunctions caused by UB (damaged vtable due to memory operations) at the disadvantage of not being able to make this choice at運行。 CRTP 生成的類可能具有標准的 memory 布局。

只要具體的類保持良好的格式,這里就沒有問題。 class AbstractBase可以用於類型擦除和作為公共接口,而class Baseclass A可能是某些組件功能的單元本地實現。

暫無
暫無

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

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