C Virtual Template Methods: Tackling Template and Runtime Polymorphism
In C , faced with the dilemma of combining template specialization with runtime polymorphism, developers encounter a stumbling block. This intricacy arises when attempting to implement virtual methods within an abstract class that accept template parameters. The challenge stems from the sheer number of potential types instantiating the template function, thus hindering the compiler's ability to dynamically dispatch calls.
To overcome this limitation, multiple approaches can be pursued. One option involves removing dynamic polymorphism and using a non-derived type to store key-value pairs. The base class template can then be used to resolve these mappings:
<code class="cpp">class AbstractComputation { public: template <typename T> void setData(const std::string& id, T value) { m_store.setData(id, value); } template <typename T> T getData(const std::string& id) const { return m_store.getData<T>(id); } protected: ValueStore m_store; };</code>
Alternatively, you can preserve runtime polymorphism while eliminating template parameters by employing type erasure. Utilizing boost::any, for example, allows for the creation of concrete, non-templated functions that accept type-erased arguments:
<code class="cpp">class AbstractComputation { public: template <typename T> void setData(const std::string& id, T value) { setDataImpl(id, boost::any(value)); } template <typename T> T getData(const std::string& id) const { boost::any res = getDataImpl(id); return boost::any_cast<T>(res); } protected: virtual void setDataImpl(const std::string& id, const boost::any& value) = 0; virtual boost::any getDataImpl(const std::string& id) const = 0; };</code>
Type erasure, essentially, allows boost::any to store data of any type behind the scenes while enabling type-safe data retrieval.
The above is the detailed content of Here are a few question-based titles that fit the content of your article: * C Virtual Template Methods: How to Achieve Template Specialization with Runtime Polymorphism? * C Template and Runtime. For more information, please follow other related articles on the PHP Chinese website!