I would like to write a macro in c++ which would give the value 0 to every element of a table. For instance, having declared i thus: int i[10];, the macro fill_with_zeros(i) would produce this effect:
i[0] = 0;
i[1] = 0; and so on.
This is its code:
#define fill_with_zeros(xyz) \
for(int l = 0 ; l < sizeof(xyz) / sizeof(int) ; l++) \
xyz[l] = 0;
The problem is that I want it to work with tables of multiple types: char, int, double etc. And for this, I need a function that would determine the type of xyz, so that instead of sizeof(int) I could use something like sizeof(typeof(xyz)).
Similar threads exist but people usually want to print the type name whereas I need to use the name within sizeof(). Is there any way to do it?
Thanks in advance
Why do you think you need a macro for that? This should work:
// Beware, brain-compiled code ahead!
template< typename T, std::size_t sz >
inline void init(T (&array)[sz])
{
std::fill( array, array+sz, T() );
}
I'd expect my std lib implementation to optimize std::fill() to call std::memset() (or something similar) on its own if T allows it.
Note that this does not actually zero the elements, but uses a default-constructed object for initialization. This achieves the same for all types that can be zeroed, plus works with many types that cannot.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With