C++ standard & size of a template array

Feb 13, 2012 at 6:25pm
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.
Feb 13, 2012 at 6:51pm
Hi

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

Last edited on Feb 13, 2012 at 7:05pm
Feb 13, 2012 at 6:59pm
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 Feb 13, 2012 at 6:59pm
Feb 13, 2012 at 7:11pm
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?
Feb 13, 2012 at 8:16pm
But the SizeOf function doesn't work inside that function because array is a pointer.
Feb 13, 2012 at 9:02pm
If you want to keep track easily of a fixed size array use std::array
Feb 13, 2012 at 10:45pm
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
Feb 14, 2012 at 1:42am
For the size of a C-style array, the C++ standard library has std::extent in <type_traits>
Feb 14, 2012 at 3:50am
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.