CRTP 模式 但是在数据结构中存储非同构类型

CRTP Pattern yet store inhomogenous types in a datastructure

本文关键字:存储 同构 类型 数据结构 模式 CRTP      更新时间:2023-10-16

我有兴趣了解CRTP。 我想为引擎实现一个组件系统,但我不想访问组件统一风格

GetComponent("withThisName");

而是在编译时(虚幻风格)

GetComponent<FromThisType>();

虽然实现 CRTP 相当容易,但我并不真正了解如何在不再次引入动态调度的情况下在数据结构中管理 CRTP 派生类。

Wiki 描述了一个带有形状的示例:

// Base class has a pure virtual function for cloning
class Shape {
public:
virtual ~Shape() {};
virtual Shape *clone() const = 0;
};
// This CRTP class implements clone() for Derived
template <typename Derived>
class Shape_CRTP : public Shape {
public:
virtual Shape *clone() const {
return new Derived(static_cast<Derived const&>(*this));
}
};
// Nice macro which ensures correct CRTP usage
#define Derive_Shape_CRTP(Type) class Type: public Shape_CRTP<Type>
// Every derived class inherits from Shape_CRTP instead of Shape
Derive_Shape_CRTP(Square) {};
Derive_Shape_CRTP(Circle) {};

在这个例子中,我仍然可以做类似的事情

std::vector<Shape*> shapes;

但是再次存在虚函数,这正是我首先试图摆脱的。我的结论是,我可能仍然没有正确使用CRTP,或者当它被使用时,另一方面,我看到虚幻引擎在使用它

,我想使用它的方式。

CRTP习语并不意味着为您提供非同类类的通用接口。这几乎都是关于静态多态性的,但结果类型彼此完全不同。
考虑一下:

template<typename T>
struct CRTP { /* ... */ };
struct A: CRTP<A> {};
struct B: CRTP<B> {};

AB没有任何共同点,它们是不同的类型,除非你给它们一个通用接口作为基类,否则你不能将它们存储在容器中(这是你建议的,即使你不喜欢它)。
它们是同一类模板的两个专用化这一事实并不能为您提供一种通过简单地忽略它们是不同类型的事实来将它们存储在某个地方的方法。

可能,CRTP不是您要找的。相反,请考虑使用类型擦除来实现您的目的。
举一个最小的工作示例:

#include <type_traits>
#include <utility>
#include <memory>
#include <vector>
class Shape {
template<typename Derived>
static std::unique_ptr<Shape> clone_proto(void *ptr) {
return std::unique_ptr<Shape>(new Derived{*static_cast<Derived *>(ptr)});
}
public:
template<typename T, typename... Args>
static std::enable_if_t<std::is_base_of<Shape, T>::value, std::unique_ptr<Shape>>
create(Args&&... args) {
auto ptr = std::unique_ptr<Shape>(new T{std::forward<Args>(args)...});
ptr->clone_fn = &Shape::clone_proto<T>;
return ptr;
}
std::unique_ptr<Shape> clone() {
return clone_fn(this);
}
private:
using clone_type = std::unique_ptr<Shape>(*)(void *);
clone_type clone_fn;
};
struct Rectangle: Shape {};
struct Circle: Shape {};
int main() {
std::vector<std::unique_ptr<Shape>> vec;
vec.push_back(Shape::create<Rectangle>());
vec.push_back(Shape::create<Circle>());
auto other = vec.at(0)->clone();
}

如您所见,在这种情况下,派生类的类型实际上被擦除了,您从create函数中得到的是一个Shape,仅此而已。Circles 和Rectangles 是Shapes,您可以轻松创建Shapes.根本没有虚函数的向量,
但仍然向内部数据成员进行双重调度,clone_fn返回正确的类型并正确克隆对象。

多态性是该语言的一个(让我说)特性,它实际上允许用户擦除一堆类型并在运行时正确调度任何函数调用。如果你想在编译时擦除类型,你可以这样做,但它不是(也不能完全)免费的。此外,它没有任何魔力:如果你想擦除一个类型,你需要一个调解器,它知道这个类型是什么,并且能够让它恢复正常工作(虚拟方法或静态函数充当调度程序或其他什么,如果你想以某种方式使用该类型,你无法避免它们)。