mercredi 1 janvier 2020

Array size deduction

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:

  1. (side question) What's (&) for? Removing would trigger error: creating array of references, which it seems to be forbidden
  2. What's wrong with myUsage signature?

Aucun commentaire:

Enregistrer un commentaire