C++知道编译时给定类型的对象数
C++ know the number of objects of a given type at compile time
我想注册给定类的所有对象,以便以后可以使用静态方法来迭代它们。我想出了下面的解决方案。 这个想法是,我将把这个类提供给与我一起工作的其他人,他们将派生这个类来设计自己的模块。但是,我必须将指针数组初始化为较大的大小,因为我不知道将创建多少个此类对象。有没有办法在编译时找出创建的对象数,如果它们都是静态声明的?
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);
}
相关文章:
- std::unordered_map 类型对象声明期间出现"field has incomplete type"错误
- C++ 多态模板类,模板类型对象的实例化
- 如何分配适合容纳 T 类型对象的缓冲区(可能过度对齐、可能有运算符 new 等)
- 如何构造一个 std::variant 类型对象,其自身 Templated 和构造函数转发参数
- C++:初始化指向具有不同类型对象的指针数组
- 在类 C++ 中构造的模板类型对象
- 如何将颁发者名称设置为x509_req类型对象
- 将任何数据类型/对象作为参数传递以确定其大小
- 将引用类型对象的数组从C#封送到C++
- <T> 从类型对象创建类型<T1>对象的构造函数
- C++是否有现有的方法来检查对象是否是派生类型对象
- C 模板:创建与现有对象相同的类型对象
- 链接列表中的虚函数 - 多种返回类型(对象)
- 没有适当操作员()的类型对象的呼叫
- 制作垫子类型对象的数组.输出窗口显示同一帧
- 抽象类型对象的分配
- 在std::list中就地创建自定义类型对象
- 接受泛型列表类型对象的参数
- C++-将模板类型对象强制转换为特定的数据类型
- 试图在C++中打印存储在类型对象数组中的信息