1

I have a simple function to shuffle elements in an std::array

template <typename T, uint size>
void Shuffle(std::array<T, size> &arr) {
    for (uint i = 0; i < arr.size() - 1; i++)
    {
        std::swap(arr[i], arr[Random(i, arr.size())]);
    }
}

make/g++ doesn't like the way I'm declaring this, giving the error "variable or field Shuffle declared void." From what I've found, this is probably an irrelevant error message, but I can't figure out what's actually wrong here.

2
  • 2
    Is uint a defined type? Did you try replacing it with std::size_t? Commented Mar 20, 2021 at 8:37
  • 1
    The code will also have a problem when an empty array is passed. Since i is unsigned, arr.size() - 1 will underflow and will lead to a very long loop and invalid array access. Consider writing i + 1 < arr.size() instead. Commented Mar 20, 2021 at 11:31

1 Answer 1

3

uint doesn't match the type of the 2nd template parameter of std::array, which is std::size_t. This causes template argument deduction failing when calling Shuffle, unless you specify template arguments explicitly.

You should declare the 2nd template parameter with type std::size_t. e.g.

template <typename T, std::size_t size>
void Shuffle(std::array<T, size> &arr)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.