mercredi 22 août 2018

Print out a class using template

I've got a problem when printing out all the values of the class

#include <iostream>

const int LENGTH = 5;

template <typename T1, typename T2>
class Test {
private:
  T1 a;
  T2 b;

public:
  void setData(T1 a, T2 b)
  {
   this->a = a;
   this->b = b;
  }
  T1 get_a() { return a; }
  T2 get_b() { return b; }
  T2 sum() const;
  Test operator*(const Test& t0);
  friend std::ostream& operator<<(std::ostream& output, const Test<T1, T2>& t0);
};

template <typename T1, typename T2>
T2 Test<T1, T2>::sum() const
{
  return a + b;
}

template <typename T1, typename T2>
Test<T1, T2> Test<T1, T2>::operator*(const Test& t0)
{
 Test<T1, T2> t;
 t.a = this->a * t0.a;
 t.b = this->b * t0.b;
 return t;
}

template <typename T1, typename T2>
std::ostream& operator<<(std::ostream& output, const Test<T1, T2>& t0)
{
  output << t0.get_a() << ", " << t0.get_b() << std::endl;
  return output;
}

int main(int argc, char *argv[])
{
  Test<int, float> t1;
  t1.setData(3, 4.5);
  Test<int, float> t2;
  t2.setData(5, 6.7);
  Test<int, float> t3 = t1 * t2;
  std::cout << t1;
}

The last line it show me an error "undefined reference to operator<< ...". I think the error comes from the friend function of the class but i don't know how to fix it. Anyone can help me, please. I appreciate for your support, thank you!

Aucun commentaire:

Enregistrer un commentaire