1

The following code can be compiled and executed by gcc:

#include <stdio.h>

template <typename T>
T&  f1(T & t) {
  printf("T\n");
  return t;
} 

extern int a[];

int main()
{
    f1(a);


    return 0;
}

But produced error when compiled by VC++2010:

1>------ Build started: Project: cpptest, Configuration: Debug Win32 ------
1>  proc1.cpp
1>  cpptest.cpp
1>c:\work\cpptest\cpptest\cpptest.cpp(18): error C2664: 'f1' : cannot convert parameter 1 from 'int []' to 'int (&)[1]'
1>  Generating Code...
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

The main issue is that the function template parameter is a reference type meaning the array argument cannot decay to a pointer type. What should be the standard behaviour according to C++03? If it is allowed, what should be the type of T, which is now an incomplete array type, inside the function f1() and its return type?

EDIT: In C++ array passed-by-reference does not decay to a pointer according to this link. Is it true here?

Community
  • 1
  • 1
JavaMan
  • 4,494
  • 4
  • 34
  • 62
  • Your code compiles fine with VS2012. So, probably an issue with VS2010. – Algirdas Preidžius Nov 24 '16 at 10:09
  • But I don't understand why it works! Isn't that the array cannot decay to a pointer inside the function template f1() since the declared parameter is a reference type? How can a function return an array type? – JavaMan Nov 24 '16 at 10:13
  • The reference to an array is not an array... – W.F. Nov 24 '16 at 10:19
  • @JavaMan, Why do you think that it can't decay to a pointer? It has already decayed to a pointer by the time it got to the function body. Relevant read: [what is array decaying?](http://stackoverflow.com/questions/1461432/what-is-array-decaying). – Algirdas Preidžius Nov 24 '16 at 10:20
  • @ Algirdas Preidžius, as mentioned in your link http://stackoverflow.com/questions/17752978/exception-to-array-not-decaying-into-a-pointer. "An Array cannot decay to a pointer when it is passed-by-reference" – JavaMan Nov 24 '16 at 10:29
  • On my Visual Studio 2015 it won't compile - wait a second, works fine. – Zebrafish Nov 24 '16 at 10:52

0 Answers0