I am working on some embedded code for which I can't use the STL containers. I have several 2D arrays whose size is known at compile time and want to write a template function to clear them. However, I can't get it to work. Here's what I tried:
template <std::size_t sizeA, std::size_t sizeB>
void clearArray(float a[sizeA][sizeB])
{
float* begin = &a[0][0];
std::fill_n(begin, sizeA * sizeB, 0.0);
}
int main()
{
float f[5][6];
clearArray(f);
for (int i = 0; i < 5; ++i)
for (int j = 0; j < 6; ++j)
cout << f[i][j] << " ";
}
However, the compiler can't successfully perform argument lookup:
test.cpp(22): error C2784: 'void clearArray(float [sizeA][sizeB])' : could not deduce template argument for 'float [sizeA][sizeB]' from 'float [5][6]' 1> test.cpp(13) : see declaration of 'clearArray'
Is there a way to do this? I know I could use sizeof(f)/sizeof(float)
to get the number of elements, or I could specify the dimensions manually, but I was hoping to make it as simple as possible.
Also, I tested this in VS2012 but the compiler for this embedded system does not support C++11.
When you pass array to function, it will decay to pointer (in this case it will become float (*a)[sizeB]
, the infomation about size will be lost, that's why the compiler could not deduce template argument. You can change it from pass by value to pass by reference, which will keep the size of array:
template <std::size_t sizeA, std::size_t sizeB>
void clearArray(float (&a)[sizeA][sizeB])
LIVE
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