从基类调用派生类模板化方法
CRTP: Call derived class templated method from base
请帮我解决以下问题:
我有一个类声明为:
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>() );
}
};
来自GenericComponent
的get()
方法应该调用来自Rim<GEAR_TYPE>
类的DummyEquation()
模板化方法。但是它的实现方式不工作-编译器报告在尝试转换到派生类时该指针的constness问题…
如何让这个工作?我已经尝试了几乎所有可能的const限定符位置,但没有解决我的问题。还有一件事要提-方法create<>()
不能被限定为const
(create<>() const
),因为它修改了它的所有者类的内容…
提前感谢任何愿意帮助我的人…欢呼声马丁
this
是指向const
对象的指针(在get
的范围内)。在继承层次结构中将其向下强制转换不会改变结果对象的const
-ness。
所以DummyEquation
&
create
必须为const
成员函数,否则get
必须为非const
。
相关文章:
- 在模板基类中为继承类中的可选重写生成虚拟方法
- 为什么此派生对象无法访问基类的后递减方法?
- 使用基类中的派生方法运行线程,而无需使用模板
- 将子类方法声明为基类的友元
- 是否可以使用基类非虚拟方法中的派生类虚拟方法?
- 在派生类中使用基类的私有成员变量的最佳方法
- 如何在成为指向基类的指针后保留对子类方法的使用?
- 从基类实例调用派生类方法而不进行强制转换
- 继承:调用基类的成员和方法
- 通过基类接受方法转发派生 UniquePtr 的右值会移动引用而不是复制
- 引用基类模板的成员变量的简单方法
- C++ 使用派生类方法更改基类数据成员
- C++初始化之前派生类调用基类的方法
- 将派生类方法与基类unique_ptr一起使用
- 为什么派生类的实例从基类调用方法?
- 基类可以声明虚拟方法但不定义它吗?仍然在派生类中定义
- googletest:测试基类具有纯虚拟方法的派生类时的核心转储
- 从基类调用重写的方法
- 为什么允许将派生类的方法static_cast为基类的方法?
- C++-从方法基类调用派生类中的重写方法