Martin Kopecký Martin Kopecký - 3 months ago 27
C++ Question

CRTP: Call derived class templated method from base

please help me with the following problem:

I have a class declared as:

template<typename GEAR_TYPE>
class Rim
: /* Derive from GenericComponent Design perspective using CRTP */
public Design::GenericComponent<Rim<GEAR_TYPE>>
{
public:
template<typename IDENTIFICATION_TAG>
typename Base::Parameter<typename IDENTIFICATION_TAG::UnitType, typename IDENTIFICATION_TAG::DataType>::QuantityType & DummyEquation( void )
{
return( Base::Parameter<typename IDENTIFICATION_TAG::UnitType, typename IDENTIFICATION_TAG::DataType>::QuantityType::from_value( 222 ) );
}
};


which inherits from
Design::GenericComponent<>
using CRTP. Within Design::GenericComponent<> there is a method:

template<typename DERIVED_COMPONENT_TYPE>
class GenericComponent
{
public:
template<typename PARAM_IDENTIFICATION>
std::shared_ptr<Base::Parameter<typename PARAM_IDENTIFICATION::UnitType, typename PARAM_IDENTIFICATION::DataType>> get( void ) const
{
mParameters.template create<PARAM_IDENTIFICATION>( static_cast<const DERIVED_COMPONENT_TYPE *>( (this) )->template DummyEquation<PARAM_IDENTIFICATION>() );
}
};


The
get()
method from
GenericComponent
should call the
DummyEquation()
templated method from the derived
Rim<GEAR_TYPE>
class. But the way it is implemented as listed does not work - compiler reports troubles with constness of this pointer when trying to cast to derived class...

How to get this working? I have tried almost every possible const qualifier placements but nothing solved my problem. Just one more thing to mention - the method
create<>()
cannot be qualified as
const
(
create<>() const
) as it modifies the content of it's owner class...

Many thanks in advance to anyone willing to help me... Cheers Martin

Answer

this is a pointer to a const object (in the scope of get). Casting it down the inheritance hierarchy doesn't change the const-ness of the resulting object.

So either DummyEquation & create need to be const member functions, or get needs to be non-const.

Comments