不同的c++类,其中成员只在类型上不同
Different c++ classes where a member only differs by type
这可能是一个非常简单的问题,但我不确定该搜索什么来找到解决方案。我有三个类,如下所示:
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));
}
}
相关文章:
- 访问C++中的类型成员
- 具有 STL 向量类型成员的类的复制内存
- 重载具有 2 个相同数据类型成员的构造函数
- std::void_t 和嵌套的非类型成员
- 返回对常量结构(指针类型)成员的引用:明显的左值到右值转换
- 使用各种数据类型成员创建对象的简便方法
- 将类类型成员定义为公共和私有之间有什么区别?
- 结构类型成员的默认构造函数中的默认参数
- 如何传递模板模板非类型成员函数指针
- 文本类类型成员函数约束
- 给定仅包含布尔类型成员的结构的两个对象 s1 和 s2,只要 s1 的成员为 true,请检查 s2 的每个成员是否为真
- 如何在 c++ 中使用二进制文件输入/输出读取/写入结构的字符串类型成员
- C++:将模板参数的模板类型成员加为好友的语法正确吗
- C++静态结构类型成员初始化
- C++:作为引用或指针的基类型成员变量
- 左值引用类型成员的用户定义移动构造函数
- 具有指针类型成员的类在 MSVS2012@debug 下销毁时失败.程序错误或错误源
- CRTP -- 访问不完整的类型成员
- 为什么C++默认初始化不对非类类型成员进行零初始化
- 请求非类类型成员