Click here to Skip to main content
15,890,512 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I know of two ways to deal with friend function of a template class.
The first way is make the friend function inline:
header file A.h

C++
#ifndef A_H
#define A_H
#include<iostream>
using namespace std;
template <class T>
class A
{
	friend ostream& operator << (ostream& outs, const A<T>& object)
	{
		//definition goes here
	}
	//Other functions of class A
}
#endif //A_H


Implementation file A.cpp

C#
//the rest of the function definition of class A


The second way is forward declare class A and the friend function and then you put the friend function definition and other definitions of functions of class A in implementation file
header file A.h

C++
#ifndef A_H
#define A_H
#include<iostream>
using namespace std;
template <class T>
class A;
template <class T>
ostream& operator << (ostream& outs, const A<T>& object);
class A
{
	friend ostream& operator << <>(ostream& outs, const A<T>& object);
	//Other functions of class A
}
#endif //A_H


Implementation file A.cpp

C++
#ifndef A.CPP
#define A.CPP
//the friend function definition and other function definitions
#endif //A.CPP


What I dont understand is, in normal classes you can always define the friend functions after the classes definition. In template classes you either have to define friend function inside the template class or forward declare the friend function. Is there an explanation for this?

What I have tried:

These are the only two ways I know. Can anyone explain how they work and if there is another way?
Posted
Updated 21-Aug-16 2:37am

1 solution

The reason is because the template is not a class definition, it is a template that is used to create a class definition. It is only when you declare the actual class, which includes the declaration of the type (T) does the compiler actually create the class definition. If the friend declaration is outside the class then there is no guarantee that the type will match what has been declared in the class.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900