#include <iostream>
class CPrivate
{
int setAge(int age)
{
std::swap(age, this->age);
return age;
}
int age{ 123 };
};
template<class Obj, class AgeType, AgeType age, class SetAgeType, SetAgeType setAge>
struct CTest
{
friend int getAge(Obj& obj)
{
return (obj.*age);
}
friend int setAgeFun(Obj &obj, int age)
{
return (obj.*setAge)(age);
}
};
template CTest<CPrivate, decltype(&CPrivate::age), &CPrivate::age, decltype(&CPrivate::setAge), &CPrivate::setAge>;
int getAge(CPrivate& test);
int setAgeFun(CPrivate &test, int age);
int main()
{
CPrivate test;
std::cout << getAge(test) << std::endl;
std::cout << setAgeFun(test, 256) << std::endl;
std::cout << getAge(test) << std::endl;
return 0;
}
总结:
- 模板显示实例化可以访问私有变量
- friend 使得可以先将定义写在类内 后续待显示实例化后, 在声明即可。