我能否以某种方式将 Curiously Recurring Template Pattern (CRTP) 与数组一起使用?
我想要的是?我想要具有某些 foo 函数的类数组。并为数组中的所有对象调用它。像这样:
template<class Derived>
struct Base{
void call(){
static_cast<Derived*>(this)->call();
}
};
struct A : Base<A>{
void call(){
cout <<"A";
}
};
struct B : Base<B>{
void call(){
cout <<"B";
}
};
...
Base array[2] = {A(), B()}; // <-- here is my array
array[0].call();
array[1].call();
附言我还阅读了有关 AutoList 模式的信息。但这似乎与我的问题无关。
最佳答案
你不能有数组
Base array[2];
自 Base
不是一个类。
Base<A>
和 Base<B>
是类,但两者是完全不同的类,它们之间没有任何关系。
更新
你可以使用类似@yzt 建议的东西,但那几乎没有比以下更优雅:
struct Base {
virtual void call () = 0;
};
struct A : Base {
void call () {
cout << "A";
}
};
struct B : Base {
void call () {
cout << "B";
}
};
Base* a [] = {new A(), new B()};
a[0]->call ();
a[1]->call ();
CRTP 类根本不需要存在。
关于数组中的 C++ CRTP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23533064/