Following an example from Scott Meyer's "Modern C++", I'd exploit std::array
size deduction with templates. I'm stumbled trying to compile my myUsage
function usage.
#include <array>
#include <iostream>
template <typename T, std::size_t N>
constexpr std::size_t arraySize(T (&) [N]) noexcept
{
return N;
}
void scottUsage()
{
int b[5];
std::array<short, arraySize(b)> c;
std::cout << arraySize(b) << " = " << c.size() << "\n";
}
template <typename T, std::size_t N>
void myUsage(T & arr [N])
{
for (auto i=0; i<arraySize(arr); i++)
std::cout << arr[i] << "\t";
}
int main()
{
scottUsage();
int a[7];
myUsage(a);
}
So two questions arise:
- (side question) What's
(&)
for? Removing would triggererror: creating array of references
, which it seems to be forbidden - What's wrong with
myUsage
signature?
Aucun commentaire:
Enregistrer un commentaire