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
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:
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:
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;
};
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