Connecting Tech Pros Worldwide Forums | Help | Site Map

Problem with defining template friend function of a template class.

PengYu.UT@gmail.com
Guest
 
Posts: n/a
#1: Nov 9 '05
The following program works with g++3.3. I'm assuming g++-3.4 is more
standard conforming that g++-3.3. Would you please tell me what is
right way to declare a template friend function of a template class?

Thanks,
Peng

#include <iostream>

template <typename T>
class A{
private:
A(){}
T _a;
public:
friend A *makeA<T>();//error in g++-3.4, works with g++3.3
};

template <typename T>
A<T> *makeA(){
return new A<T>;
}

int main ( void ) {
makeA<int>();
}


Neelesh
Guest
 
Posts: n/a
#2: Nov 9 '05

re: Problem with defining template friend function of a template class.


PengYu.UT@gmail.com wrote:[color=blue]
> #include <iostream>
>
> template <typename T>
> class A{
> private:
> A(){}
> T _a;
> public:
> friend A *makeA<T>();//error in g++-3.4, works with g++3.3
> };
>
> template <typename T>
> A<T> *makeA(){
> return new A<T>;
> }
>
> int main ( void ) {
> makeA<int>();
> }[/color]


The C++ standard states that if a template function is a friend of a
class then the function must be declared before the class definition.

Hence for this code to compile, you will need to add following two
lines before the class definition :

template <class T> class A; // declare the class since it is used in
function's prototype
template<class T> A<T>* makeA(); // declare the function

This would solve the problem.

John Harrison
Guest
 
Posts: n/a
#3: Nov 9 '05

re: Problem with defining template friend function of a template class.


Neelesh wrote:[color=blue]
> PengYu.UT@gmail.com wrote:
>[color=green]
>>#include <iostream>
>>
>>template <typename T>
>>class A{
>> private:
>> A(){}
>> T _a;
>> public:
>> friend A *makeA<T>();//error in g++-3.4, works with g++3.3
>>};
>>
>>template <typename T>
>>A<T> *makeA(){
>> return new A<T>;
>>}
>>
>>int main ( void ) {
>> makeA<int>();
>>}[/color]
>
>
>
> The C++ standard states that if a template function is a friend of a
> class then the function must be declared before the class definition.
>
> Hence for this code to compile, you will need to add following two
> lines before the class definition :
>
> template <class T> class A; // declare the class since it is used in
> function's prototype
> template<class T> A<T>* makeA(); // declare the function
>
> This would solve the problem.
>[/color]

I don't know about gcc 3.4 but it's a good idea on some compilers to use
this very similar version

template <class T> class A;
template <class T> A<T>* makeA();

template <typename T>
class A
{
friend A* makeA<>();
};

Note that <> has replaced <T> in the friend declaration.

john
Closed Thread