FIX: Template Friend Function Causes Compiler Error C2248 (166109)



The information in this article applies to:

  • Microsoft Visual C++, 32-bit Enterprise Edition 5.0
  • Microsoft Visual C++, 32-bit Professional Edition 5.0

This article was previously published under Q166109

SYMPTOMS

The compiler generates a compiler error C2248 as follows:
Error C2248: 'member' : cannot access member declared in class 'class'
under the following circumstances:

  • If a class declares a template function as a friend function, and
  • If the template function definition appears after the class definition.

RESOLUTION

Do not declare a template function as a friend of a class.

STATUS

Microsoft has confirmed that this is a problem in the Microsoft products that are listed at the beginning of this article. This problem was corrected in Microsoft Visual C++ version 6.0.

MORE INFORMATION

The following sample demonstrates the problem and the workaround.

Sample Code

   /*
   Compile option: None
   */ 

   class X;

   template <class T> void AFunction(X &x, T &t);

   class X
   {
   private:

      int m_n;

   public:

      template <class T> friend void AFunction(X &x, T &t) ;

   };

   template <class T> void AFunction(X &x, T &t)
   {

      x.m_n = t; // C2248 here.

   }

   int main()
   {
      X x;
      int n;
      AFunction(x, n);

           return 0 ;
   }

				
NOTE: Defining the template function before the class definition eliminates the compiler error C2248. But the compiler does not generate any code when you call the template function.

Modification Type:MinorLast Reviewed:7/5/2005
Keywords:kbBug kbfix kbVC600fix KB166109