MoCha wrote:
hello everyone,
i want to know of any trick used to restrict the access scope of a
friend class (or function). ie instead of the friend class having
access to the entire internals of the class in question, let it have
access to a few private/protected members.
You could collect those members and their accessors in separate classes,
and let them grant friendship as appropriate. Let those separate
classes be public bases of your "target" class. Your derived class need
declare any new friends.
#include <iostream>
struct Int_wrapper
{
friend std::ostream& operator << (
std::ostream&, Int_wrapper const& );
Int_wrapper( int i ): m_i( i ) { }
protected:
int value( ) const { return m_i; }
private:
int m_i;
};
struct Instance_counte d_int_wrapper: Int_wrapper
{
using Int_wrapper::va lue;
Instance_counte d_int_wrapper( int i =0 ):
Int_wrapper( i ) { ++m_count; }
~Instance_count ed_int_wrapper( ) { --m_count; }
int count( ) const { return m_count; }
private:
static int m_count;
};
int Instance_counte d_int_wrapper:: m_count = 0;
std::ostream& operator << ( std::ostream& out, Int_wrapper const& p )
{
return out << p.value( );
}
int main( )
{
Instance_counte d_int_wrapper i( 3 );
std::cout << i << '\n';
}