Friends of Template Classes

A problem that I have been struggling with for some days one. When I declare a template function as a friend of a template class, I'll get a compile error, such as 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.

#include <iostream>

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

template <typename U>
std::ostream& operator<< (std::ostream &os, const test<U> &t)
{
    std::cout << t.val;
    return os;
}
Contact Us
  • SenseTime Research, Shenzhen Bay Eco-Technology Park
  • cshzxie [at] gmail [dot] com