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

I am trying to create a template that will allow me to use the resizable array. Is there any way to find sizeof (T)? I use malloc, not the new one, because I want to use realloc in a function that resizes the array. This is the constructor for my class that gets errors:

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

When you try to build, the following error message appears:

 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 call it with:

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

From the research I did, it looks like the compiler does not know what to use for sizeof (T), so it cannot compile. How else will I do this?

+1
c ++ templates
Nov 03 '11 at 10:18
source share
3 answers

malloc returns void* , and while C is allowed to assign incompatible pointers, C ++ does not. You need to tell T* result of malloc, assuming arr is defined as T* .

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

There is no problem calling sizeof(T) inside the template as long as T completed at the instance point (and int is the fundamental type, it is always completed).

+13
Nov 03 '11 at 10:20
source share

I think you are analyzing the problem too much. It just tells you that you need to pass the void* returned by malloc to type T* arr .

+1
Nov 03 2018-11-11T00:
source share

Of course you can. This is not the cause of your mistake.

I assume the set::arr member is of type T* . Since you created an instance of the set class with an int template parameter type, declaring this member variable becomes int *arr; . C ++, unlike C , does not allow you to implicitly cast from void * into another type of pointer. Therefore, you will need to display the result of calling malloc .

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

Also, remember that when you insert elements into a set, you need to use the new location to create the elements in the selected buffer, and then explicitly call their destructors when copying / moving / deleting.

+1
Nov 03 2018-11-11T00:
source share



All Articles