C Virtual Template Method
In C , it can be challenging to combine static time polymorphism (templates) with runtime polymorphism. This is evident in the following abstract class:
<code class="cpp">class AbstractComputation { public: template <class T> virtual void setData(std::string id, T data); template <class T> virtual T getData(std::string id); };</code>
This class aims to set and retrieve data of a specified type based on a unique identifier. However, a problem arises when attempting to call the generic setData function with a specific type, such as setData
The language prohibits this construct because the compiler would have to dynamically dispatch an infinite number of possible template instantiations. To resolve this issue, several approaches are possible:
Removing Static Polymorphism:
<code class="cpp">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>
Removing Dynamic 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>
The above is the detailed content of How can you achieve polymorphism with virtual template methods in C ?. For more information, please follow other related articles on the PHP Chinese website!