在C++中创建模板时是否可以找到sizeof(T)?

Dom*_*m12 1 c++ templates

我正在尝试构建一个模板,让我使用可调整大小的数组.有没有办法找到sizeof(T)?我正在使用malloc而不是new,因为我想在调整数组大小的函数中使用realloc.这是我的类的构造函数,它正在收到错误:

template <class T>
set<T>::set(void) {
arr = malloc(10 * sizeof(T));
numElts = 0;
size = 10;
};
Run Code Online (Sandbox Code Playgroud)

尝试构建时收到以下错误消息:

error C2440: '=' : cannot convert from 'void *' to 'int *'
1>          Conversion from 'void*' to pointer to non-'void' requires an explicit cast
1>          c:\set.cpp(42) : while compiling class template member function 'set<T>::set(void)'
1>          with
1>          [
1>              T=int
1>          ]
Run Code Online (Sandbox Code Playgroud)

在主函数中,我用它调用它:

set<int> *set1 = new set<int>();
Run Code Online (Sandbox Code Playgroud)

从我所做的研究来看,编译器似乎无法知道用于sizeof(T)的内容,因此无法编译.我怎么会这样呢?

K-b*_*llo 17

malloc返回一个void*,而C允许分配不兼容的指针,而C++则不然.你需要转换T*为malloc的结果,假设arr定义为T*.

arr = static_cast< T* >( malloc(10 * sizeof(T)) );
Run Code Online (Sandbox Code Playgroud)

sizeof(T)在模板内调用没有问题,只要T在实例化时完成(并且int是基本类型,它总是完整的).

  • 工作代码:`arr = static_cast <T*>(malloc(10*sizeof(T)));` (2认同)