#include <iostream>
template <typename type, int size>
class testClass
{
type num[size];
public:
testClass(std::initializer_list<type> list)
{
int i = 0;
for (auto elem : list) {
num[i] = elem;
i++;
}
}
friend std::ostream& operator<< (std::ostream &stream, const testClass<type, size>& test);
};
template<typename type, int size>
std::ostream& operator<< (std::ostream &stream, const testClass<type, size>& test)
{
for (int i = 0; i < size; i++) {
stream << test.num[i];
}
}
int main()
{
testClass<int, 3> test{ 1, 2, 3 };
std::cout << test;
}
My code results in a linking error even though I seem to have correctly declared a friend function inside a templated class. This is a simplified program to demonstrate the problem.
I know there are multiple solutions to this and one of them is by writing template <typename type, int size> before the friend declaration. My question is, why does this work?
I am new to template programming and so it's just tough to grasp why this works and why my original code does not work.
This declaration
declares a non-template friend function. It is the class itself that is a template but not the friend function.
You need either to define it within the definition of the class
testas for example (such a friend function defined in a template class is called templated entity):or for each used specialization of the class
testfor which the friend function is called to define the non-template friend function outside the class as for examplePay attention to that your friend function shall return a reference to the stream.
Here are demonstration programs.
and
The output of the both programs is