C++知道编译时给定类型的对象数

C++ know the number of objects of a given type at compile time

本文关键字:类型 对象 编译 C++      更新时间:2023-10-16

我想注册给定类的所有对象,以便以后可以使用静态方法来迭代它们。我想出了下面的解决方案。 这个想法是,我将把这个类提供给与我一起工作的其他人,他们将派生这个类来设计自己的模块。但是,我必须将指针数组初始化为较大的大小,因为我不知道将创建多少个此类对象。有没有办法在编译时找出创建的对象数,如果它们都是静态声明的?

class Module {
    static Module* module_list[];
    static int count;
public:
    Module(string str){
        id = count;
        name = str;
        module_list[count++] = this;
    }
    static void printModules(){
        for(int i = 0; i < count; i++)
            cout << module_list[i]->name << endl;
    }
    int id;
    string name;
};
Module* Module::module_list[256];
int Module::count = 0;
Module x("module x"), y("module y");
int main(){
    Module::printModules();
}

注意:我最初的目标是在编译时创建列表本身,但是,我不知道如何做到这一点。欢迎提出建议。

有没有办法在编译时找出创建的对象数,如果它们都是静态声明的?

不是真的,因为对象可能在单独的翻译单元中实例化。即使不是,目前也无法反映特定的翻译单元并在C++中查找特定对象的所有实例化(除非您要使用外部解析器 + 代码生成器解决方案(。


但是,我必须将指针数组初始化为较大的大小,因为我不知道将创建多少个此类对象。

只需使用std::vector,因此您不需要任何固定限制:

auto& getModuleList()
{
    static std::vector<Module*> result;
    return result;
}

class Module {        
public:
    Module(string str){
        id = count;
        name = str;
        getModuleList().emplace_back(this);
    }