"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How can you achieve polymorphism with virtual template methods in C++?

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

Published on 2024-11-08
Browse:470

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:

class AbstractComputation {
    public:
        template  virtual void setData(std::string id, T data);
        template  virtual T getData(std::string id);
};

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:
class AbstractComputation {
public:
   template 
   void setData( std::string const & id, T value ) {
      m_store.setData( id, value );
   }
   template 
   T getData( std::string const & id ) const {
      return m_store.getData( id );
   }
protected:
   ValueStore m_store;
};

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:
class AbstractComputation {
public:
   template 
   void setData( std::string const & id, T value ) {
      setDataImpl( id, boost::any( value ) );
   }
   template 
   T getData( std::string const & id ) const {
      boost::any res = getDataImpl( id );
      return boost::any_cast( res );
   }
protected:
   virtual void setDataImpl( std::string const & id, boost::any const & value ) = 0;
   virtual boost::any getDataImpl( std::string const & id ) const = 0;
};
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3