訪問控制不適用於參數明確模板實例([temp.explicit]/12
)。這可以被利用來給私有成員公共接入(courtesy of litb):
首先,一些設置代碼:
template<typename Tag>
struct result {
/* export it ... */
typedef typename Tag::type type;
static type ptr;
};
template<typename Tag>
typename result<Tag>::type result<Tag>::ptr;
template<typename Tag, typename Tag::type p>
struct rob : result<Tag> {
/* fill it ... */
struct filler {
filler() { result<Tag>::ptr = p; }
};
static filler filler_obj;
};
template<typename Tag, typename Tag::type p>
typename rob<Tag, p>::filler rob<Tag, p>::filler_obj;
現在的Point
定義:
class Point
{
public:
Point() : m_i(0) {}
void PrintPrivate(){cout << m_i << endl; }
private:
int m_i;
};
現在result<Pointm_i>::ptr
通過明確填寫實例化rob<Pointm_i, &Point::m_i>
- 這是一個明確的模板實例,因此訪問控制不適用:
個
struct Pointm_i { typedef int Point::*type; };
template class rob<Pointm_i, &Point::m_i>;
和訪問私有成員:
void ChangePrivate (Point &i) { (i.*result<Pointm_i>::ptr)++; }
int main()
{
Point sPoint;
sPoint.PrintPrivate();
ChangePrivate(sPoint);
sPoint.PrintPrivate();
}
究竟爲什麼你需要做到這一點? – chris
添加公共getter/setter! –
請參閱http://bloglitb.blogspot.ro/2010/07/access-to-private-members-thats-easy。HTML –