假设class X我想要返回内部成员的访问权限:
class Z
{
// details
};
class X
{
std::vector<Z> vecZ;
public:
Z& Z(size_t index)
{
// massive amounts of code for validating index
Z& ret = vecZ[index];
// even more code for determining that the Z instance
// at index is *exactly* the right sort of Z (a process
// which involves calculating leap years in which
// religious holidays fall on Tuesdays for
// the next thousand years or so)
return ret;
}
const …Run Code Online (Sandbox Code Playgroud) 我有重复相同代码const和非const版本的问题.我可以用一些代码来说明问题.这里有两个样本访问者,一个修改访问对象,另一个不访问.
struct VisitorRead
{
template <class T>
void operator()(T &t) { std::cin >> t; }
};
struct VisitorWrite
{
template <class T>
void operator()(const T &t) { std::cout << t << "\n"; }
};
Run Code Online (Sandbox Code Playgroud)
现在这里是一个聚合对象 - 这只有两个数据成员,但我的实际代码要复杂得多:
struct Aggregate
{
int i;
double d;
template <class Visitor>
void operator()(Visitor &v)
{
v(i);
v(d);
}
template <class Visitor>
void operator()(Visitor &v) const
{
v(i);
v(d);
}
};
Run Code Online (Sandbox Code Playgroud)
并且有一个函数来演示以上内容:
static void test()
{
Aggregate a;
a(VisitorRead());
const Aggregate …Run Code Online (Sandbox Code Playgroud)