0

I know this is a common question, but how do I pass a std::array as a function parameter? I've looked at answers for other questions on here asking the same thing, and the best "solution" I found was to use a template to set size_t to a keyword like SIZE. I tried this, but it still gives me two compile time errors:

Error   C2065   'SIZE': undeclared identifier
Error   C2975   '_Size': invalid template argument for 'std::array', expected compile-time constant expression

Both errors on the line where I have my void function definition.

As far as I know, I did this exactly how the solution was typed out. I know I could instead pass through a std::vector, but I'm stubborn and want to learn this.

Here is my relevant code:

#include <iostream>
#include <array>
using namespace std;

template<size_t SIZE>
void QuickSort(array<unsigned, SIZE>& arrayName);

int main()
{
    // main function.
}

void QuickSort(array<unsigned, SIZE>& arrayName)
{
    // whatever the function does.
}

I'd appreciate any help figuring out what it is that I'm doing wrong.

EDIT: I forgot to take out the second function parameter. I did that, but still the same issues.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • A function whose job is to sort some data probably should not be restricted to taking an `std::array` or `std::vector`. A function can handle both (and, potentially, some other container type that you haven't thought of yet) if it takes two **iterators** to designate the sequence of objects to be sorted. – Pete Becker Apr 26 '22 at 12:41

1 Answers1

3

Your function definition still needs template parameters since the compiler has no way of knowing what SIZE is

template<size_t SIZE>
// ^^^^^^^^^^^^^^^^^^
void QuickSort(array<unsigned, SIZE>& arrayName)
{
/// whatever the function does.
}
康桓瑋
  • 33,481
  • 5
  • 40
  • 90
  • Thank you ! This solved my issue perfectly. I was unaware I had to template it on every instance of the function. – Rodrigo Ponce Apr 26 '22 at 02:05
  • @RodrigoPonce if you separate the function's declaration from its definition, yes. Templates are typically written inline instead. You could move your definition above `main()` and get rid of the separate declaration, eg: `template void QuickSort(array& arrayName) { ... } int main() { ... /* use QuickSort() */ ... }` – Remy Lebeau Apr 26 '22 at 02:29