我正在尝试从 CRTP 基内部访问派生类类型,例如:
template <typename CRTP>
class Base {
using Type = typename CRTP::Type;
void method(const Type& t) {
do_something();
static_cast<CRTP&>(*this).derived_method( t );
}
void do_something() {
}
};
class Derived : public Base<Derived> {
using Type = int;
void derived_method(const Type& t ) {
}
};
这不起作用,因为 CRTP 在 Base 的声明中不完整。我理解这个错误。是否有合理的解决方法来获得类似的效果?
我在C++静态多态性(CRTP)和使用派生类的typedefs中看到类似的问题,但该解决方案在我的情况下不起作用。对于这个问题,基类正在寻找 Derived 的模板参数,而不是内部类型,因此特征类无需查看 Derived 的声明内部即可获取该类型。
我能想到的一切都涉及以一种或另一种方式重复
Derived::Type = int
的定义,而不是使用 Derived 中已有的内容。
我不完全确定这是否是您所需要的,但它会延迟
CRTP
类的使用,直到完成:
#include <type_traits>
template <typename CRTP>
class Base {
public:
void method(const auto& t) {
static_assert(std::is_same_v<std::remove_cvref_t<decltype(t)>,
typename CRTP::Type>);
do_something();
static_cast<CRTP&>(*this).derived_method(t);
}
void do_something() {
}
};