在我目前的代碼,我是從enable_shared_from_this
派生的TNCPConnection
類:CRTP模式和enable_shared_from_this
class TNCPConnection : public boost::enable_shared_from_this<TNCPConnection> { ... };
現在我需要創建一個第二類ETCPConnection
將與現有TNCPConnection
同學分享了很多代碼。所以明顯的解決方案是有一個抽象基類CPConnectionBase
,它實現了通用功能。
我知道繼承層次結構中只有一個類可以從enable_shared_from_this
派生。在尋找解決方案時,我偶然發現了CRTP模式,但我不確定是否正確理解了這一點。這是我的方法:
template <class Derived>
class CPConnectionBase : public boost::enable_shared_from_this<Derived>
{
public:
CPConnectionBase(void) { }
virtual ~CPConnectionBase(void) = 0 { }
};
class TNCPConnection : public CPConnectionBase<TNCPConnection> { ... };
class ETCPConnection : public CPConnectionBase<ETCPConnection> { ... };
這是解決我的問題的正確方法嗎?引用計數能否正確地使用這種方法?特別是我想知道enable_shared_from_this
的模板參數是否必須是Derived
(如上例所示)或類似CPConnectionBase<Derived>
?