🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: grads
Article #6

Why doesn't this simple program compile?

#6
From: Ching-Tsun Chou
Date: Thu, 31 Aug 1995 23:44
78 lines
2322 bytes

I'm reading S.B. Lippman's book "C++ Primer" (2nd ed.) and trying out
the example programs in it using gcc-2.7.0.  According to Lippman's book,
the following simple program should compile, though when executed it should
fail at the line marked by "// ERROR".  But I couldn't even compile it
using gcc-2.7.0.  If the program is in a file "prog.cc", then compiling it
with "g++ prog.cc" generates the following error message:

  prog.cc: In function `int main()':
  prog.cc:50: type unification failed for function template
  `template <class Type> void swap(Array<...> &, int, int)'

where line 50 is the line marked by "// ERROR".  What is wrong?

I'd appreciate any comments!

- Ching Tsun

PS. Please send your replies to <chou@cs.ucla.edu>.

PPS. The same program without template did compile and produced the
     expected results when executed.

================================= prog.cc =================================

#include <assert.h>
#include <iostream.h>

const int ArraySize = 12;

template <class Type>
class Array
{
  public:
    Array( int sz = ArraySize )
      { size = sz; ia = new Type[size]; }
    ~Array()
      { delete [] ia; }
    Array& operator=( const Array& );
    virtual Type& operator[]( int i )
      { return ia[i]; }
    int getSize()
      { return size; }
  protected:
    int size;
    Type *ia;
};

template <class Type>
class ArrayRC : public Array<Type>
{
  public:
    ArrayRC( int sz = ArraySize )
      : Array<Type>( sz ) {} ;
    Type& operator[]( int i )
      { assert( i >= 0 && i < size ); return ia[i]; }
};

template <class Type>
void swap( Array<Type> &A, int i, int j )
{
  Type tmp = A[i]; A[i] = A[j]; A[j] = tmp;
}

main()
{
  Array<int> ia1;
  ArrayRC<int> ia2;
  
  cout << "swap with Array ia1" << endl ;
  swap( ia1, 1, ia1.getSize() );
  
  cout << "swap with ArrayRC ia2" << endl ;
  swap( ia2, 1, ia2.getSize() );    // ERROR
  
  return 0;
}
Technical Details
Message-ID: <425hh1$joo@delphi.cs.ucla.edu>
Path: arc1-ca.pugleaf.net!delphi.cs.ucla.edu!chou

Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!delphi.cs.ucla.edu!chou
From: chou@cs.ucla.edu (Ching-Tsun Chou)
Newsgroups: grads,gnu.g++.help,comp.lang.c++
Subject: Why doesn't this simple program compile?
Date: 31 Aug 1995 23:44:33 GMT
Organization: UCLA Computer Science Dept.
Message-ID: <425hh1$joo@delphi.cs.ucla.edu>
NNTP-Posting-Host: pelican.cs.ucla.edu