C++ standard & size of a template array

Hi!

Many people browsing through these forums are familiar with the sizeof-operator in C++. The use of it is simple:

sizeof(int); // Return the size of int.

And, if you want to get the size of an int array, you use the sizeof-operator like this:

sizeof(array) / sizeof(array[0]); // Return the size of int array.

As you know, this only works with int arrays. Fortunately, C++ contains templates, so why can get the size of an array of any type. Here's a typical implementation:

1
2
3
4
template<typename T, std::size_t S>
std::size_t SizeOf(T(&)[S]){
	return S;
}


Now, to the question. Why C++ standard library does not have this kind of function? This is somewhat useful, general use function after all.
Hi

than add it youtself to STL - :) , STL is open source.

Last edited on
When you create the array you have to know the size of the array so there is never a need to use such a function.
Last edited on
Here's an example where the size of template array would be helpful:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
template<typename T>
T* UniqueRand(T array[], const T min, const T max){
	for(unsigned int i = 0; i < SizeOf(array); i++){
		do{ // Do at least one draw:
			array[i] = ::fmod(::rand(), max);
		}while(array[i] < min);
		for(unsigned int j = 0; j < i; j++){
			while((array[i] == array[j]) || (array[i] < min)){
				array[i] = ::fmod(::rand(), max);
			}
		}
	}
	return array;
}


What do think?
But the SizeOf function doesn't work inside that function because array is a pointer.
If you want to keep track easily of a fixed size array use std::array
std::array of different size are different types. So you will be making a lot of functions (that will need to be templatized),
¿what consequences does this have?
You could use std::vector instead, if you can handle that overhead of dynamic allocation.

When working with arrays and functions you've got several options
_ Use a centinel that marks the end
_ Pass the size of the array
_ Pass a pointer to the end/pass the end
For the size of a C-style array, the C++ standard library has std::extent in <type_traits>
As you know, this only works with int arrays.


Actually, that method works with any array.

As has been noted above, in your UniqueRand example SizeOf(array) is equivalent to SizeOf(T*) because despite naming the parameter array, it is only a pointer.

Topic archived. No new replies allowed.