-1

Is there a way for the Visual Studio compiler to determine the template parameter M without passing the size of the array as a template parameter to a templatized function like how gcc can determine?

To give an example -

template<unsigned M>
void multiply(
 double A[M][M],
 double B[M][M]
)
{
..........
}

A and B are arrays in the above example. So for the above example, in gcc if you call the above function as multiply(A, B); the code compiles successfully whereas in visual studio you get a compiler error - "no overloaded function found".

But in visual studio only if you call the above function as multiply<M>(A, B); where M is the size of arrays A and B, the code compiles successfully.

So basically my question is that is there a way to call the function as multiply(A, B); successfully in visual studio without passing the template parameter 'M'?

Tried calling the function 'multiply' as multiply(A, B); in visual studio and expected it to work but it did not.

  • 2
    I saw this question yesterday. – 273K Apr 27 '23 at 20:54
  • Your assertions about the behavior of GCC and MSVC are (generally) wrong. Please show a [mre] of the code that you actually try to compile. In particular the behavior will obviously depend on the types of `A` and `B`. – user17732522 Apr 27 '23 at 20:56
  • In C++, using `type[N]` as input parameter is very problematic. Just use something else like `std::array` – ALX23z Apr 27 '23 at 20:57
  • Arrays generally decay to pointers when passed as parameters. Is the decay supposed to happen before or after template deduction? – BoP Apr 27 '23 at 20:59
  • @BoP On the argument it happens for the purpose of deduction before any deduction if the function parameter is not a reference, and not at all otherwise. It always happens on the parameter before any deduction. Therefore OP's approach (with some reasonable assumptions) should actually be fine. – user17732522 Apr 27 '23 at 21:07
  • Pass the arrays by reference, that will allow the compiler to deduce their size – Remy Lebeau Apr 27 '23 at 21:43

1 Answers1

3

double A[M][M] in a parameter is not an array, it's a pointer. Use a reference to an array, then M will be determined:

template<unsigned M>
void multiply(
  double (&A)[M][M],
  double (&B)[M][M]
) {
}

int main() {
  double a[2][2]{};
  multiply(a, a);
}
273K
  • 29,503
  • 10
  • 41
  • 64
  • 1
    But the way OP passes the 2D arrays - like `double A[M][M]` - should decay to `double (*A)[M]`. It still has `M` in it - why Visual Studio compiler cannot deduce it? – Eugene Apr 27 '23 at 22:47