【问题标题】:is it possible to create an array of type declarations in c++?是否可以在 C++ 中创建类型声明数组?
【发布时间】:2020-03-31 00:39:11
【问题描述】:

我想知道是否有一种方法可以创建一个包含类型声明的数组,以便更轻松、更灵活地声明大量不同类型的变量。

例如,我想做的是有一个父类的数组,我想声明一个父类的子类的动态指针数组。

这是一个示例类声明:

class parent {
   private:
      int x;
}

class child1 : public parent {
   private:
      int y;
}

class child2 : public parent {
    private:
      int z;
}

这是我手动执行的操作:

parent *array[100];
int count = 0;
int child1_num = 25, child2_num = 75;
for (int i = 0; i < child1_num; i++) {
   parent[count++] = new child1;
} 
for (int i = 0; i < child2_num; i++) {
   parent[count++] = new child2;
}

我希望我能以类似于以下的形式获得它:

parent *array[100];
child_type type[2] = {child1, child2};
int child_num[2] = {25, 75};
int count  = 0;
for (int i = 0; i < 2; i++) {
   for (int j = 0; j < child_num[i]; j++) {
       array[count++] = new type[i];
   }
}

如果有更好的方法来解决这个问题?我想不出别的办法。

【问题讨论】:

标签: c++ arrays c++11 inheritance


【解决方案1】:

是的,这是可能的,但您不需要类型列表。还有其他方法可以改进您的代码。首先使用基本的 c++11 功能,例如,std::vector 而不是数组,std::unique_ptr 而不是裸指针。

#include <memory>
#include <vector>

int main()
{
    std::vector<std::unique_ptr<parent>> v;
    int child1_num = 25, child2_num = 75;
    for (int i = 0; i < child1_num; i++) {
        v.emplace_back(new child1);
    } 
    for (int i = 0; i < child2_num; i++) {
        v.emplace_back(new child2);
    }

    return 0;
}

然后你可以更进一步,创建一个类似的函数

template<typename T, typename Vector>
void fill(Vector& v, size_t count)
{
    for (int i = 0; i < count; i++) {
        v.emplace_back(new T);
    }
}

并简化您的主要代码

    std::vector<std::unique_ptr<parent>> v;
    int child1_num = 25, child2_num = 75;
    fill<child1>(v, child1_num);
    fill<child2>(v, child2_num);

然后停在这里。就够了。你不需要类型列表。不要忘记parent 中的虚拟析构函数。

【讨论】:

    【解决方案2】:

    是的,你可以,通过类型列表(首先在 Andrei Alexandrescu 的 Modern C++ Design 一书中普及)。见:Type list with boost

    【讨论】:

      猜你喜欢
      • 2015-08-20
      • 1970-01-01
      • 1970-01-01
      • 2012-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-16
      • 2014-11-15
      相关资源
      最近更新 更多