gpt4 book ai didi

数组中的 C++ CRTP

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:45:02 29 4
gpt4 key购买 nike

我能否以某种方式将 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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com