friends and templates

S

Solid

Hi, I use g++ 3.4.2:
g++ -v
Reading specs from /usr/local/lib/gcc/i386-portbld-freebsd4.10/3.4.2/specs
Configured with: ./..//gcc-3.4-20040723/configure --disable-nls
--with-system-zlib --with-libiconv-prefix=/usr/local
--program-suffix=34 --with-gxx-include-dir=/usr/local/lib/gcc/i386-portbld-freebsd4.10/3.4.2/include/c++/
--disable-shared --disable-libgcj --prefix=/usr/local
i386-portbld-freebsd4.10
Thread model: posix
gcc version 3.4.2 20040723 (prerelease) [FreeBSD]

I tried to declare a friend helper, which has access to private class
data, but it does not work:

$cat try.cpp
#include <iostream>
using namespace std;
template <typename T> void f(T);
template <typename T> class A {
public:
A(T t) : x_(t) {}
friend void f<> (A&); // <> used to specify a template
private:
T x_;
};
template <typename T>
void f(A<T>& t) { cout << t.x_ << endl; }
int main () {
A<int> x(1);
f(x);
}

$g++ try.cpp
try.cpp: In function `void f(A<T>&) [with T = int]':
try.cpp:15: instantiated from here
try.cpp:9: error: `int A<int>::x_' is private
try.cpp:12: error: within this context

Help please
 
J

Jordan Stewart

your declaration of f doesn't match it's definition...
try this:

#include <iostream>

template <typename T> class A;

template <typename T> void f( A<T>& );

template <typename T> class A {
public:
A(T t) : x_(t) {}

friend void f<> ( A& );

private:
T x_;
};

template <typename T>
void f( A<T>& t ) {
std::cout << t.x_ << std::endl;
}

int main () {
A<int> x(1);
f(x);

return 0;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,074
Latest member
StanleyFra

Latest Threads

Top