不同的c++类,其中成员只在类型上不同

Different c++ classes where a member only differs by type

本文关键字:类型 成员 c++      更新时间:2023-10-16

这可能是一个非常简单的问题,但我不确定该搜索什么来找到解决方案。我有三个类,如下所示:

class class_double_array {
public:
    double *value;
    int height;
    int width;
    void alloc(const int &h, const int &w);
}

class class_int_array {
public:
    int *value;
    int height;
    int width;
    void alloc(const int &h, const int &w);
}

class class_logical_array {
public:
    bool *value;
    int height;
    int width;
    void alloc(const int &h, const int &w);
}

其中alloc

void class_double_array::alloc(const int &h, const int &w) {
    width = w;
    height = h;
    value = (double*)calloc(h*w,sizeof(double));
}
在c++中有标准的方法来组织这些类吗?这是一个非常简化的例子,但我有类似的东西,类方法基本上是相同的,但取决于value的类型。在这个例子中,我必须为每个类重写alloc,即使它基本上为每个类做同样的事情。我正在寻找使用模板,但我不能找到我要找的东西。

像这样:

template<typename T>
class T_array
{
public:
    T *value;
    int width;
    int height;
    void alloc(const int &h, const int &w)
    {
        width = w;
        height = h;
        value = (T*)calloc(h*w, sizeof(T));
    }
}