Type Polymorphism in C : Virtual Template Methods
In C programming, combining virtual member functions with class templates can be challenging. This situation arises when you want to dynamically dispatch methods based on runtime type information, but still maintain type-safe behavior.
The Problem
Consider the following abstract class and its derived implementation:
<code class="cpp">class AbstractComputation { public: template <class T> virtual void setData(std::string id, T data) = 0; template <class T> virtual T getData(std::string id) = 0; }; class Computation : public AbstractComputation { public: template <class T> void setData(std::string id, T data); template <class T> T getData(std::string id, T data); };</code>
The intention here is that calling setData
Possible Solutions
1. Remove Static Polymorphism:
One approach is to eliminate static polymorphism (templates) and introduce a generic store for key-value pairs:
<code class="cpp">class ValueStore { template <typename T> void setData(std::string const & id, T value); template <typename T> T getData(std::string const & id) const; }; class AbstractComputation { public: template <typename T> void setData(std::string const & id, T value) { m_store.setData(id, value); } template <typename T> T getData(std::string const & id) const { return m_store.getData<T>(id); } protected: ValueStore m_store; };</code>
This solution provides dynamic polymorphism without the need for template specialization.
2. Remove Dynamic Polymorphism:
Another option is to maintain runtime polymorphism but remove static polymorphism:
<code class="cpp">class AbstractComputation { public: template <typename T> void setData( std::string const & id, T value ) { setDataImpl( id, boost::any( value ) ); } template <typename T> T getData( std::string const & id ) const { boost::any res = getDataImpl( id ); return boost::any_cast<T>( res ); } protected: virtual void setDataImpl( std::string const & id, boost::any const & value ) = 0; virtual boost::any getDataImpl( std::string const & id ) const = 0; };</code>
Here, type erasure using boost::any allows for dispatching to non-templated methods without sacrificing type safety.
The above is the detailed content of How to Achieve Type-Safe Dynamic Dispatch with Virtual Template Methods in C ?. For more information, please follow other related articles on the PHP Chinese website!