【发布时间】:2017-01-06 23:38:14
【问题描述】:
对于一个类如
namespace JDanielSmith {
class C
{
const size_t _size;
const std::unique_ptr<int[]> _data;
public:
C(size_t size) : _size(size), _data(new int[size]) {}
inline const int* get() const noexcept { return _data.get(); }
inline int* get() noexcept { return _data.get(); }
size_t size() const noexcept { return _size; }
};
}
公开迭代的首选方式是什么?我应该写begin()/end()(和cbegin()/cend())成员函数吗?
const int* cbegin() const {
return get();
}
const int* cend() const {
return cbegin() + size();
}
或者这些应该是非成员函数?
const int* cbegin(const C& c) {
return c.get();
}
const int* cend(const C& c) {
return cbegin(c) + c.size();
}
begin()/end() 是否应该同时具有const 和非const 重载?
const int* begin() const {
return get();
}
int* begin() {
return get();
}
还有其他需要考虑的事情吗?是否有工具/技术可以使这种“易于正确处理”并减少样板代码的数量?
一些相关的问题/讨论包括:
【问题讨论】:
-
两者都应该有;成员以及免费(或在添加 free 版本之前考虑是否适合您的情况使用
std::begin和std::end对)。此外,您还应该有begin()和end()对。还有,成员类型,iterator和const_iterator而不是const int*左右。 -
@SteveJessop:不。我根本没有意思。我说的是一般意义上的:如果
std::begin不适合你,那么你应该在同一个命名空间中添加你的,这样 ADL 才能工作。 -
@Dan:对于您发布的代码,您不必编写免费版本,因为
std::beginfamily 可以正常工作。