」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何在 C++ 中使用虛擬模板方法實現多態性?

如何在 C++ 中使用虛擬模板方法實現多態性?

發佈於2024-11-08
瀏覽:976

How can you achieve polymorphism with virtual template methods in C  ?

C 虛擬模板方法

在C 中,將靜態時間多態性(模板)與運行時多態性結合起來可能具有挑戰性。這在以下抽象類別中很明顯:

class AbstractComputation {
    public:
        template  virtual void setData(std::string id, T data);
        template  virtual T getData(std::string id);
};

此類旨在根據唯一識別碼設定和擷取指定類型的資料。但是,當嘗試使用特定類型呼叫通用 setData 函數時會出現問題,例如 setData("foodouble", data)。

該語言禁止此構造,因為編譯器必須動態地調度無限數量的可能的模板實例。要解決這個問題,可以採用以下幾種方法:

刪除靜態多態性:

  • 透過引入單獨的類型來儲存鍵值來消除靜態多態性映射。然後,模板可以在基礎層級解決這個問題,而不需要多態性:
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;
};

刪除動態多態性:

  • 保留運行時多態性,但透過類型擦除消除靜態多態性:
  • 利用boost::any,它提供類型擦除,以儲存任何類型的資料:
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