How to define and use a friend function to a temlate class with the same template?

Posted by Narek on Stack Overflow See other posts from Stack Overflow or by Narek
Published on 2010-06-15T07:17:36Z Indexed on 2010/06/15 7:22 UTC
Read the original article Hit count: 230

Filed under:
|
|
|

I have written the following code:

#include <iostream>
using namespace std;

template <class T>
class AA
{
  T a;

public:
AA()
{
 a = 7;
}

friend void print(const AA<T> & z);
};

template <class T>
void print(const AA<T> & z)
{
    cout<<"Print: "<<z.a<<endl;
}

void main()
{
AA<int> a;
print<int>(a);
}

And getting the following error:

error C2248: 'AA<T>::a' : cannot access private member declared in class 'AA<T>'
1>        with
1>        [
1>            T=int
1>        ]
1>        c:\users\narek\documents\visual studio 2008\projects\aaa\aaa\a.cpp(7) : see declaration of 'AA<T>::a'
1>        with
1>        [
1>            T=int
1>        ]
1>        c:\users\narek\documents\visual studio 2008\projects\aaa\aaa\a.cpp(30) : see reference to function template instantiation 'void print<int>(const AA<T> &)' being compiled
1>        with
1>        [
1>            T=int
1>        ]

What's wrong?

© Stack Overflow or respective owner

Related posts about c++

Related posts about function