gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:05:18 24 4
gpt4 key购买 nike

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

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

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

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> ]

在主函数中,我调用它:

set<int> *set1 = new set<int>();

根据我所做的研究,编译器似乎无法知道对 sizeof(T) 使用什么,因此无法编译。我还能怎么办呢?

最佳答案

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

arr = static_cast< T* >( malloc(10 * sizeof(T)) );

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

关于c++ - 在 C++ 中创建模板时是否可以找到 sizeof(T)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8002615/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com