我正在探索 C++23 中引入的新推断功能,并试图了解如何将其与奇异循环模板模式 (CRTP) 有效结合,以实现多态行为,而无需依赖传统的虚函数。
我的目标是以类型擦除或半多态的方式管理派生对象(例如形状、处理器等)的集合,同时仍然可以获得静态多态性的好处,并可能减少间接和动态分配。
#include <vector>
#include <iostream>
template <typename Derived>
struct Base {
void process(this Derived& self) {
self.impl(); // supposed to call derived's impl()
}
};
struct DerivedA : Base<DerivedA> {
void impl() {
std::cout << "DerivedA::impl\n";
}
};
struct DerivedB : Base<DerivedB> {
void impl() {
std::cout << "DerivedB::impl\n";
}
};
int main() {
std::vector</* ??? */> collection;
collection.push_back(DerivedA{});
collection.push_back(DerivedB{});
for (auto& obj : collection) {
obj.process(); // call the correct impl() for each type
}
}
我知道这std::variant
是一种解决方法,但我正在寻找其他高性能解决方案。理想情况下,我希望避免动态分配和虚函数的开销,并使用现代 C++23 特性(例如使用 CRTP 推断这一点)来获得静态多态性的好处。