Friends of Template Classes

A problem that I have been struggling with for some days. When I declare a template function as a friend of a template class, I'll get a compile error, such as the following:

#include <iostream>

template < typename T >
  class test {
    private:
      int val;
    public:
      friend std::ostream &
    operator << (std::ostream & os,
      const test < T > & t);
  };

template < typename T >
  std::ostream &
operator << (std::ostream & os,
  const test < T > & t) {
  std::cout << t.val;
  return os;
}

And I'll get a compile error message: undefined reference to 'operator< <(std::ostream&, test const&)'

Finally, I found that we couldn't declare a friend function like that, we need to specify a different template type for it.

Contact Us
  • Tencent AI Lab, Shenzhen, China
  • cshzxie [at] gmail [dot] com