C Virtual Template Method
The scenario presented involves an abstract class with virtual template methods, setData and getData, intended to dynamically set and retrieve data of various types based on a provided identifier. However, as the question acknowledges, such a construct is not directly supported in C .
To address this limitation, there are two primary approaches:
Remove Static Polymorphism
One option is to remove static polymorphism (templates) and introduce an intermediate storage mechanism. The AbstractComputation class could define a non-templated ValueStore, responsible for storing and retrieving data based on identifiers:
<code class="cpp">class ValueStore { public: template <typename T> void setData(std::string const &id, T value) {...} template <typename T> T getData(std::string const &id) {...} }; 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); } private: ValueStore m_store; };</code>
Deriving classes can then directly access the ValueStore without the need for runtime polymorphism.
Remove Runtime Polymorphism
Alternatively, runtime polymorphism can be retained while removing static polymorphism. This involves performing type erasure on the base class:
<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>
boost::any is a type that can store values of any type and allows for safe retrieval of the data. Type erasure is performed by passing boost::any objects as arguments to the virtual methods, which must be implemented in the derived classes.
The above is the detailed content of How to Implement Virtual Template Methods in C ?. For more information, please follow other related articles on the PHP Chinese website!