www.digitalmars.com         C & C++   DMDScript  

c++ - Template problems

reply "Piyush" <justsovanilla yahoo.co.in> writes:
Hi,
I just wrote a  generic program to sort an array of
numbers(integers....floats doubles etc)....it doesn't seem to be compiling
on Visual c++ 6  the syntax used is similar to that used in Lippmann and
Lajoie(C++ primer) if any one could help me out I'd really appreciate it.
/* program to sort numebers */
#include<iostream>
using namespace std;
template <typename T,int size>
T sort( T (&arr)[size] )
{
 int i,j;
 T tmp;
 for(i=0;i<size-1;i++)
  for(j=0;size-i;j++)
   if(arr[j]>arr[j+1])
   {
    tmp=arr[j];
    arr[j]=arr[j+1];
    arr[j+1]=tmp;
   }
}
int main()
{
 int a[5]={5,3,4,2,1};
 int b[5]={5.9,6.7,1.2,4.2,0.5};
 sort(a);
 sort(b);
 for(int i=0;i<5;i++)
  cout<<a[i]<<" b= "<<b[i]<<endl;
 return 0;
}

the error i am getting is:
c:\dm\progs\3sem\oops\x.cpp(4) : error C2265: '<Unknown>' : reference to a
zero-sized array is illegal
c:\dm\progs\3sem\oops\x.cpp(21) : error C2784: 'T __cdecl sort(T (&)[1])' :
could not deduce template argument for ' (&)[1]' from 'int [5]'
c:\dm\progs\3sem\oops\x.cpp(22) : error C2784: 'T __cdecl sort(T (&)[1])' :
could not deduce template argument for ' (&)[1]' from 'int [5]'
Error executing cl.exe.
Oct 31 2003
parent "Walter" <walter digitalmars.com> writes:
Your program compiles successfully using DMC++, which you can download from
www.digitalmars.com/download/freecompiler.html.

It crashes when it runs, though, because the inner for loop never terminates
and increments j until it crashes.

"Piyush" <justsovanilla yahoo.co.in> wrote in message
news:bntgbn$1omp$1 digitaldaemon.com...
 Hi,
 I just wrote a  generic program to sort an array of
 numbers(integers....floats doubles etc)....it doesn't seem to be compiling
 on Visual c++ 6  the syntax used is similar to that used in Lippmann and
 Lajoie(C++ primer) if any one could help me out I'd really appreciate it.
 /* program to sort numebers */
 #include<iostream>
 using namespace std;
 template <typename T,int size>
 T sort( T (&arr)[size] )
 {
  int i,j;
  T tmp;
  for(i=0;i<size-1;i++)
   for(j=0;size-i;j++)
    if(arr[j]>arr[j+1])
    {
     tmp=arr[j];
     arr[j]=arr[j+1];
     arr[j+1]=tmp;
    }
 }
 int main()
 {
  int a[5]={5,3,4,2,1};
  int b[5]={5.9,6.7,1.2,4.2,0.5};
  sort(a);
  sort(b);
  for(int i=0;i<5;i++)
   cout<<a[i]<<" b= "<<b[i]<<endl;
  return 0;
 }

 the error i am getting is:
 c:\dm\progs\3sem\oops\x.cpp(4) : error C2265: '<Unknown>' : reference to a
 zero-sized array is illegal
 c:\dm\progs\3sem\oops\x.cpp(21) : error C2784: 'T __cdecl sort(T (&)[1])'
:
 could not deduce template argument for ' (&)[1]' from 'int [5]'
 c:\dm\progs\3sem\oops\x.cpp(22) : error C2784: 'T __cdecl sort(T (&)[1])'
:
 could not deduce template argument for ' (&)[1]' from 'int [5]'
 Error executing cl.exe.
Oct 31 2003