假设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) 你有没有恨它
class Foobar {
public:
Something& getSomething(int index) {
// big, non-trivial chunk of code...
return something;
}
const Something& getSomething(int index) const {
// big, non-trivial chunk of code...
return something;
}
}
Run Code Online (Sandbox Code Playgroud)
我们无法使用另一个方法实现这两种方法,因为您无法const从const版本中调用非版本(编译器错误).演员将被要求const从非const一个版本调用该版本.
有没有一个真正优雅的解决方案,如果没有,最接近一个?
我正在实现一个具有STL类接口的自定义容器.我必须提供一个常规迭代器和一个const迭代器.两个版本的迭代器的大多数代码都是相同的.我怎样才能避免这种重复?
例如,我的容器类是Foo,我正在实现FooIterator和FooConstIterator.两个迭代器都必须提供operator++()相同的方法.
我的问题类似于如何删除类似的const和非const成员函数之间的代码重复?但是那个问题的答案特定于const和非const方法,尤其是访问器.我没有看到这可能会如何推广到迭代器问题.
我应该FooIterator从FooConstIterator其他非const方法派生并扩展它吗?这要么导致虚拟方法或方法隐藏,这在这里似乎不合适.
也许FooIterator应该包含一个FooConstIterator.虽然这种方法确实减少了实现重复,但它似乎重新引入了许多样板方法定义.
是否有聪明的模板技术从单个定义生成两个迭代器?或许有一种方法 - 颤抖 - 使用预处理器来消除这些几乎相同的类.
我已经尝试查看我的本地STL实现,看看它是如何处理它的.有很多辅助类,我在设计中遇到了麻烦,但看起来功能很简单.
在以前的项目中,我的自定义容器是在标准STL容器之上构建的,所以我不必提供自己的迭代器.在这种情况下,这不是一个选项.
作为扩展到这个问题是const_iterators更快?,我有另一个问题const_iterators.如何删除一个常量const_iterator?虽然迭代器是指针的通用形式,但仍然const_iterator和iterators是两个不同的东西.因此,我相信,我也不能用来const_cast<>转换const_iterator为iterators.
一种方法可能是您定义一个迭代器,该迭代器将元素移动到该const_iterator点的元素.但这看起来像是一个线性时间算法.
对于实现这一目标的最佳方法有什么想法吗?