”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 如何在 C++ 中使用虚拟模板方法实现多态性?

如何在 C++ 中使用虚拟模板方法实现多态性?

发布于2024-11-08
浏览:671

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