C 虛擬模板方法
在C 中,將靜態時間多態性(模板)與運行時多態性結合起來可能具有挑戰性。這在以下抽象類別中很明顯:
class AbstractComputation {
public:
template virtual void setData(std::string id, T data);
template virtual T getData(std::string id);
};
此類旨在根據唯一識別碼設定和擷取指定類型的資料。但是,當嘗試使用特定類型呼叫通用 setData 函數時會出現問題,例如 setData
該語言禁止此構造,因為編譯器必須動態地調度無限數量的可能的模板實例。要解決這個問題,可以採用以下幾種方法:
刪除靜態多態性:
class AbstractComputation {
public:
template
void setData( std::string const & id, T value ) {
m_store.setData( id, value );
}
template
T getData( std::string const & id ) const {
return m_store.getData( id );
}
protected:
ValueStore m_store;
};
刪除動態多態性:
class AbstractComputation {
public:
template
void setData( std::string const & id, T value ) {
setDataImpl( id, boost::any( value ) );
}
template
T getData( std::string const & id ) const {
boost::any res = getDataImpl( id );
return boost::any_cast( res );
}
protected:
virtual void setDataImpl( std::string const & id, boost::any const & value ) = 0;
virtual boost::any getDataImpl( std::string const & id ) const = 0;
};
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3