boost::ptr_list中正向声明的类

Forward-declared class in boost::ptr_list

本文关键字:声明 ptr list boost      更新时间:2023-10-16

对于一个小型科学项目,我设置了一个Simulation类,它将所有模拟对象保存在ptr_list中。因为我需要快速访问所有粒子,所以我添加了一个额外的ptr_list。现在boost抱怨,因为它不喜欢前向声明类。已经向我指出了recursive_wrapper,但ptr_list< recursive_wrapper<Particle> >似乎都不起作用。

#include <boost/ptr_container/ptr_list.hpp>
class SimulatedObject {
};
class Particle; // derived from SimulatedObject
class Simulation {
public:
    void addObj(SimulatedObject *obj) {
        simulatedObjects.push_back(obj);
    }
    void addObj(Particle *par) {
        particles.push_back(par);
    }
protected:
    boost::ptr_list<SimulatedObject> simulatedObjects;
    boost::ptr_list<Particle> particles;
};
int main(int argc, char** argv) {
    Simulation sim();
}

我认为问题在于构造函数是由编译器隐式创建的,并调用ptr_list的构造函数。ptr_list构造函数使用模板化的类并需要其定义,仅向前声明是不够的。

您可以通过显式声明构造函数并仅在定义模板化类之后定义它来解决此问题。