Motivation :
通过一个 C++ 对象的指针直接访问该对象的 protected 成员变量,无需修改该类的实现,这是我们使用第三方 C++ 类库时常见的需求。
My Approch :
#define PROTECTED_CAST_DECL (CLASS_TYPE ,MEMBER_TYPE ,MEMBER_NAME ) /
template <typename ClassType , typename MemberType > /
class C ##MEMBER_NAME ##Accessor /
{ /
class CAccessor : public ClassType /
{ /
friend class C ##MEMBER_NAME ##Accessor ; /
}; /
public : /
static MemberType & GetMember (ClassType * pClass ) /
{ /
return ((CAccessor *)pClass )->MEMBER_NAME ; /
} /
};
#define PROTECTED_CAST (CLASS_TYPE ,CLASS_OBJECT_PTR ,MEMBER_TYPE ,MEMBER_NAME ) (C ##MEMBER_NAME ##Accessor <CLASS_TYPE , MEMBER_TYPE >::GetMember (CLASS_OBJECT_PTR ))
Sample :
以下示例代码展示了 PROTECTED_CAST 的使用方法,代码在 VC++ 2008 下测试通过。
class CPrivateMemberWrapper
{
protected :
int m_iValue ;
double m_dValue ;
string m_sValue ;
public :
CPrivateMemberWrapper (int i , double d , const char * lps ):
m_iValue (i ), m_dValue (d ), m_sValue (lps )
{}
~CPrivateMemberWrapper () {}
};
PROTECTED_CAST_DECL (CPrivateMemberWrapper , int , m_iValue )
PROTECTED_CAST_DECL (CPrivateMemberWrapper , double , m_dValue )
PROTECTED_CAST_DECL (CPrivateMemberWrapper , string , m_sValue )
int _tmain (int argc , _TCHAR * argv [])
{
CPrivateMemberWrapper Wrapper (1979, 3.14, "CPrivateMemberWrapper" );
cout << PROTECTED_CAST (CPrivateMemberWrapper , &Wrapper , int , m_iValue ) << endl ;
cout << PROTECTED_CAST (CPrivateMemberWrapper , &Wrapper , double , m_dValue ) << endl ;
cout << PROTECTED_CAST (CPrivateMemberWrapper , &Wrapper , string , m_sValue ) << endl ;
return 0;
}