Topic: Q: Friend of template class declaration location matters?


Author: Erik Badger <erikba@attachmate.com>
Date: 1998/03/11
Raw View
Hello,

Suppose a template class A<T> has a friend function foo() defined inside
the class definition.  A pointer to a class instantiation (A<char> *pA)
is created, and then the friend function is called.  With my compiler
(MSVC5sp3) this results in an error that foo() is not defined, as I
gather the compiler hasn't bothered to see what is actually in the class
A definition.  If there is an instantiation of the class (A<char> Ainst)
then foo is found and everything compiles fine.

I have two questions based on this:
1: Should I be able to call the friend function without such a class
instantiation?

2: According to Stroustrup: C++PL3rd C.13.8.4 "When a function is
called, its declaration can be found even if it is not in scope,
provided it is declared in the same namespace as one of its arguments."
However, having foo() take an argument of type A<char> * doesn't fix the
problem (by having A's definition scanned for foo()).  So, is this a
case of my misunderstanding, or something else.


Here is code that shows the problem:

template <class T>
class A
{
 typedef A<T> self;

 friend self& func (self& obj)
 {
  return(obj);
 }
};


int main()
{
// A<char> AInst;    // Un-commenting this makes it work
 A<char> *pA;

 func(*pA);            // Compiler error, func(A<char>) undeclared

 return(0);
}

Yes, I know that I could put the defnition of func() outside of the
class A definition, but then I don't get to see useful typedef's such as
'self' in the example.


Thanks for any help,
    -Erik
---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]