数组中的 C++ CRTP

标签 c++ arrays templates design-patterns crtp

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

相关文章:

c++ - 名称不同但参数相同的函数

c - 用于创建链表的数组

c++ - 运算符重载和继承(保持同一类型)

c++ - 如何让编译器在赋值时计算出模板类参数?

C++ 17 : Using alias template bug in gcc?

c++ - 我在 C++ 中构建 "*"数组时遇到问题

c++ - Qt C++ : removing next-to-last item from QListWidget makes program crash

c++ - std::vector<unsigned char> 到 QPixmap

java - 排序——是否可以很好地使用子数组进行排序?

Java:从索引到索引排序列表