By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,513 Members | 1,650 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,513 IT Pros & Developers. It's quick & easy.

Problem with defining template friend function of a template class.

P: n/a
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>();
}

Nov 9 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
Pe*******@gmail.com wrote:
#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.

Nov 9 '05 #2

P: n/a
Neelesh wrote:
Pe*******@gmail.com wrote:
#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.


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
Nov 9 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.