Home  >  Article  >  Backend Development  >  How can you achieve polymorphism with virtual template methods in C ?

How can you achieve polymorphism with virtual template methods in C ?

DDD
DDDOriginal
2024-10-27 06:53:03714browse

How can you achieve polymorphism with virtual template methods in C  ?

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("foodouble", data).

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:

  • Eliminate the static polymorphism by introducing a separate type to store the key-value mappings. The template can then resolve this at the base level, without the need for 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:

  • Retain runtime polymorphism but eliminate static polymorphism by type erasure:
  • Utilize boost::any, which provides type erasure, to store data of any type:
<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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn