friend template

Naoki Saito saito@math.ucdavis.edu
Thu Dec 17 16:47:00 GMT 1998


Dear ecgs developers,

I encountered the following problem and would like to know whether there
is any
workaround.  I followed exactly the same way as the FAQ (Friend
templates) suggests.
* ecgs version: 1.1b ( g++ --version produces egcs-2.91.57)
* OS linux 2.1.129
* commands
 $ g++ -o test test_main.cc test.cc
Error:
/tmp/ccozF3uA.o: In function `main':
/tmp/ccozF3uA.o(.text+0x8d): undefined reference to `float
sum<float>(Data<float> const &)'
collect2: ld returned 1 exit status

I would greatly appreciate your help!

Here is a programs (I have 3 very short files here).

//==============================================================
// test_main.cc
#include "test.h"

main()
{
  Data<float> A(10);
  int i;
  for (i = 0; i < 9; i++)
    A[i] = float(i);

  cout << "A.sum() = " << A.sum() << endl;
  cout << "sum(A) = " << sum(A) << endl;
}

//==============================================================
// test.h
#include <math.h>
#include <stream.h>

template <class DT>
class Data;

template <class DT>
DT sum(const Data<DT>&);

template <class DT>
class Data
{
protected:
 int len;
 DT *s;
public:
  Data() : len(0), s(0) {}
  Data(int n) : len(n), s(new DT[n]) {}
  virtual ~Data() { if (s != NULL) delete s; }
  int length() const { return len; }
  DT& operator[](int i) const { return s[i]; }
  DT sum() const;
  friend DT sum<>(const Data<DT>&);
};

//==============================================================
// test.cc

#include "test.h"

template Data<float>;
template Data<double>;
template Data<int>;

// This is a membership function
template <class DT> DT Data<DT>::sum() const
{
  DT res = 0;
  DT* top = &(s[len]);
  DT* t = s;
  while (t < top) res += *t++;
  return res;
}

// This is a friend function
template <class DT> DT sum(const Data<DT>& A)
{
  DT res = 0;
  DT* top = &(A.s[A.len]);
  DT* t = A.s;
  while (t < top) res += *t++;
  return res;
}

--
 Naoki Saito, Ph.D., Associate Professor, Department of Mathematics
 University of California, One Shields Avenue, Davis, CA 95616-8633 USA





More information about the Gcc-bugs mailing list