从基类调用派生类模板化方法

CRTP: Call derived class templated method from base

本文关键字:方法 基类 调用 派生      更新时间:2023-10-16

请帮我解决以下问题:

我有一个类声明为:

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

,通过CRTP继承Design::GenericComponent<>。在Design::GenericComponent<>中有一个方法:

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>() );
    }
};

来自GenericComponentget()方法应该调用来自Rim<GEAR_TYPE>类的DummyEquation()模板化方法。但是它的实现方式不工作-编译器报告在尝试转换到派生类时该指针的constness问题…

如何让这个工作?我已经尝试了几乎所有可能的const限定符位置,但没有解决我的问题。还有一件事要提-方法create<>()不能被限定为const (create<>() const),因为它修改了它的所有者类的内容…

提前感谢任何愿意帮助我的人…欢呼声马丁

this是指向const对象的指针(在get的范围内)。在继承层次结构中将其向下强制转换不会改变结果对象的const -ness。

所以DummyEquation &

create必须为const成员函数,否则get必须为非const