Click here to Skip to main content
15,883,883 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Let's say I have a class C and a container template T_CONTAINER.
I have a function in date that I only want to expose to T_CONTAINER.
How can I do this? Note that I am using Visual C++ 2010 as a compiler.

I've had to make the functions public, which is less than desirable.

I've tried:
C++
class C;
#include "T_CONTAINER.H"
class C {
     friend T_CONTAINER< C >;
}
Posted
Updated 18-May-11 5:08am
v2

1 solution

Tried the following which works.
C++
template <typename T>
class A
{
    T *_t;
public:
    A(T *t) : _t(t) {}
    void accessT()
    {
        _t->privateAccess();
    }
};
class C {
    void privateAccess()
    {
        cout << "private" << endl;
    }
    friend A<C>;
};
int main()
{
    C c;
    A<C> a(&c);
    a.accessT();
    return 0;
}

With the friend declaration, the template class can access the private methods of class C. I don't know where you went wrong.

Edit: Most container classes have some default template arguments for allocators and such. Make sure they match in your friend declaration.
 
Share this answer
 
v3
Comments
T2102 18-May-11 11:52am    
It actually looks like it's solely limited to the copy constructor. I want to avoid implicit copy construction whenever possible.
Niklas L 18-May-11 12:05pm    
I added a copy constructor to C, and it still works. Then I added a copy constructor to A, but C can still touch his private parts, so to speak. What did you do to have it not working?
T2102 18-May-11 12:33pm    
My template class contains an STL template class S. I added both A<c> and S<c> as friends just in case. When the copy constructor is private, I get the error C::C cannot access private member declared in class C. When the copy constructor is public, it compiles correctly.
T2102 18-May-11 12:33pm    
Note that the error is pointing to xmemory line 48
T2102 18-May-11 12:37pm    
I am bow guessing that an implementation detail in STL is causing the problem, but I am not sure.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900