Friend function of a template class

From: Ruben Campos (Ruben.Campos_at_robotica.uv.es)
Date: 10/28/04


Date: Thu, 28 Oct 2004 11:37:34 +0200

I have a problem with a template function that is declared as a friend of a
template class. I'll first show the exact problem with source code:

    // MyClass.hpp
template <typename T>
class MyClass
{
    // ...
    friend void MyFriendFunction (MyClass <T> * const ptrMyClass);
    // ...
};

#include "MyClass.cpp"

    // MyClass.cpp
// ...
template <typename T>
void
MyFriendFunction (MyClass <T> * const ptrMyClass)
{
    // ...
}
// ...

    // Main.cpp
#include "MyClass.hpp"

int
main (int argn, char ** argv)
{
    MyClass <float> x;

    MyFriendFunction(&x);

    return 0;
}

Although MyClass <T> is a template, I still prefer to place the
implementation of its methods in a MyClass.cpp file, and not to show them
with the class declaration. But because MyClass <T> is a template, and so it
needs method definitions visible in its header file, I include MyClass.cpp
file inside MyClass.hpp file instead of building it (I don't compile
MyClass.cpp). I've tried before this file scheme, and it works fine.

Trying to build this, I receive an linker undefined external error for the
MyFriendFunction (...) symbol. I've tried two alternative ways:

a) Including the MyFriendFunction definition directly into MyClass.hpp,
after (outside) class declaration. This returns the same linker error.

b) Including the MyFriendFunction implementation directly into declaration,
into MyClass.hpp inside class declaration. This works fine and don't return
any error.

But I don't want function implementations inside class declaration, or
merely inside a header file. Can you help me with this? Thank you very much
in advance.



Relevant Pages

  • Re: Friend function of a template class
    ... The linker undefined external error don't appear ... I supposed that MyFriendFunction was a template ... >> MyClass.hpp, after class declaration. ...
    (comp.lang.cpp)
  • Re: Errors in VC program with gdiplus
    ... template argument list ... : see declaration of 'iterator' ...
    (microsoft.public.vc.mfc)
  • Errors in VC program with gdiplus
    ... template argument list ... : see declaration of 'iterator' ...
    (microsoft.public.vc.mfc)
  • Re: OK in Visual C++6.0 but not in Visual C++ .NET 2003?
    ... The instantion of the InitClass function template with template argument ... > If I had rewritten the friend declaration inside the class as ... i.e. MyClass and MyClassare the same. ... So this syntax means that all ...
    (microsoft.public.dotnet.languages.vc)
  • Re: Type intializing with template
    ... There's a syntax error lurking in your code. ... Template definitions and declarations cause mysterious syntax errors. ... the simple error of lacking the template declaration ... > ref class X{ ...
    (microsoft.public.dotnet.languages.vc)