Is it possible to find the sizeof(T) when creating a template in C++?

c++, templates

Solution

`malloc` returns a `void*`, and while C allowed incompatible pointers to be assigned, C++ does not. You need to cast to `T*` the result of malloc assuming `arr` is defined as `T*`.

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

There is no problem in calling `sizeof(T)` within a template, as long as `T` is complete at the point of the instantiation (and `int` is a fundamental type, its always complete).

Problem

I'm trying to build a template that will let me use a resizable array. Is there a way to find the sizeof(T)? I'm using malloc rather than new because I want to use realloc in the function that resizes the array. This is the constructor for my class that is getting errors: ``` template <class T> set<T>::set(void) { arr = malloc(10 * sizeof(T)); numElts = 0; size = 10; }; ``` I get the following error message when trying to build: ``` 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> ] ``` In the main function I'm calling it with: ``` set<int> *set1 = new set<int>(); ``` From the research I've done, it looks like the compiler has no way of knowing what to use for sizeof(T), so it can't compile. How else would I go about this?

Original source