Problem with defining template friend function of a template class.

P

PengYu.UT

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>();
}
 
N

Neelesh

#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>();
}


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.
 
J

John Harrison

Neelesh said:
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.

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top