tags:

views:

143

answers:

2

How can i compile the below code without changing the status of int data?

template<typename U>
void Test(U);

template< class T > 
class B {
    int data;
    public:
    friend void Test<>( T );
};

template<typename U>
void Test(U u) {
    B < int> b1;
    b1.data = 7;
}

int main(int argc, char *argv[])
{
    char i;
    Test(i);
    system("PAUSE");    
    return 0;
}

The above code causes a compiler error, because b1.data is private in Test with U = char.

A: 

This compiled using VS2008. Not sure if it conforms to the standard.

#include <cstdlib>

template<typename U> void Test(U);

template< class T > class B {
    int data;
    public:
    template <typename U >  friend  void Test(U);
};

template<typename U>
void Test(U u){
    B < int> b1;
    b1.data = 7;
    }
int main(int argc, char *argv[])
{
    char i;
    Test(i);
    system("PAUSE");    
    return 0;
}
Vulcan Eager
+1  A: 

The problem is that you are befriending Test<U> to B<U> (for the same U), but you are trying to access the internals of a B<int> from a Test<char> (different U).

It would probably be simplest to make any Test friend of any B.

UncleBens